java - Thread-safe updating of a cached resource -
the logic pretty straightforward:
foo foo = cache.get(); if (isuptodate(foo)) { return foo; } else { foo = getupdatedfoo(); // slow or expensive cache.put(foo); return foo; }
however, want make sure that
- only 1 thread calls
getupdatedfoo()
@ time - if thread calling
getupdatedfoo()
, thread b doesn't call it, instead waiting thread a's results
i cobble based on memoizer pattern jcip, suspect there's simpler way -- possibly using guava cachebuilder? not obvious how, though.
update: implemented double-checked locking pattern per frankpl's answer below:
foo foo = cache.get(); if (!isuptodate(foo)) { lock.lock(); // block if other thread refreshing try { // see if other thread refreshed foo = cache.get(); if (!isuptodate(foo)) { // guess not, we'll refresh ourselves foo = getupdatedfoo(); cache.put(foo); } } { lock.unlock(); } } return foo;
see http://en.wikipedia.org/wiki/double-checked_locking double checked locking pattern use. instead of new helper()
used in code samples, use getupdatedfoo()
.
Comments
Post a Comment