java - my ideal cache using guava -


off , on past few weeks i've been trying find ideal cache implementation using guava's mapmaker. see previous 2 questions here , here follow thought process.

taking i've learned, next attempt going ditch soft values in favor of maximumsize , expireafteraccess:

concurrentmap<string, myobject> cache = new mapmaker()         .maximumsize(maximum_size)         .expireafteraccess(minutes_to_expiry, timeunit.minutes)         .makecomputingmap(loadfunction); 

where

function<string, myobject> loadfunction = new function<string, myobject>() {    @override    public myobject apply(string uidkey) {       return getfromdatabase(uidkey);    } }; 

however, 1 remaining issue i'm still grappling implementation evict objects if reachable, once time up. result in multiple objects same uid floating around in environment, don't want (i believe i'm trying achieve known canonicalization).

so far can tell answer have additional map functions interner can check see if data object still in memory:

concurrentmap<string, myobject> interner = new mapmaker()         .weakvalues()         .makemap(); 

and load function revised:

function<string, myobject> loadfunction = new function<string, myobject>() {    @override    public myobject apply(string uidkey) {       myobject dataobject = interner.get(uidkey);       if (dataobject == null) {          dataobject = getfromdatabase(uidkey);          interner.put(uidkey, dataobject);       }       return dataobject;    } }; 

however, using 2 maps instead of 1 cache seems inefficient. there more sophisticated way approach this? in general, going right way, or should rethink caching strategy?

whether 2 maps efficient depends entirely on how expensive getfromdatabase() is, , how big objects are. not seem out of reasonable boundaries this.

as implementation, looks can layer maps in different way behavior want, , still have concurrency properties.

  1. create first map weak values, , put computing function getfromdatabase() on map.
  2. the second map expiring one, computing, function gets first map.

do access through second map.

in other words, expiring map acts pin most-recently-used subset of objects in memory, while weak-reference map real cache.

-dg


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -