-
1. Re: Atomic read OR write
ben.wang Feb 22, 2005 11:44 AM (in response to krisjenkins)This may be difficult to do without thinking it further. If the node does not exist, for example, there is no way to lock it. Therefore, atomicity can not be achieved.
-Ben -
2. Re: Atomic read OR write
belaban Feb 22, 2005 12:32 PM (in response to krisjenkins)How about the following code:
// ReentrantLock lock;
lock.acquire();
Object val=cache.get(key);
if(val == null) {
val=fetchValueFromDB();
cache.put(node, key, val);
}
lock.release();
This simply uses external synchronization.
A more elegant solution would be to use a CacheLoader: a get() fetches the value from the DB and adds it to the cache with a write-lock. CacheLoader synchronizes access, so only 1 thread actually triggers the loading. -
3. Re: Atomic read OR write
krisjenkins Feb 22, 2005 12:32 PM (in response to krisjenkins)Ah, that's a shame. Thanks for the rapid answer though, Ben.
Cheers,
Kris -
4. Re: Atomic read OR write
krisjenkins Feb 22, 2005 12:40 PM (in response to krisjenkins)Bela,
Maybe I'm missing something, but it looks like that code fragment makes things worse. Now it will synchronize on every read, not just every read-that-requires-a-write. Is that right? And if so, would a cacheLoader suffer the same problem?
Kris -
5. Re: Atomic read OR write
belaban Feb 22, 2005 2:20 PM (in response to krisjenkins)Use a read/write lock then. The problem you are trying to solve is exactly what the CacheLoader was designed to do.
With a CacheLoader, every get() on a non-existing node, or a node marked as not-yet-loaded will access the underlying store. -
6. Re: Atomic read OR write
krisjenkins Feb 23, 2005 2:10 PM (in response to krisjenkins)I see. Thanks Bela. :-)