This package contains an implementation of an Ehcache which provides for explicit locking, using READ and WRITE locks.
It is possible to get more control over Ehcache's locking behaviour.
The initial version (0.2) works with Ehcache when used with the Terracotta Server Array. 0.3, works both with Terracotta and standalone when combined with Ehcache 2.1 or later.
When using the Ehcache APIs in standalone ehcache core, there is no direct control over locking. The last write wins. This is akin to the READ_UNCOMMITTED isolation level.
However the using the Explicit locking API uses the lock manager which as of Ehcache 2.1, has been extended to support local caching.
In this case the cache is always coherent, akin to READ_COMMITTED isolation level. This package simply gives you more control over when locks are acquired and released. In regular Ehcache if you get an object to read or write it can be changed underneath you while you are performing your application level operations on the object. p/
With this module you can first get the lock for the key, then perform your app level operations preventing anyone else from writing to the object. When the app level operations are completed you put the Element back in the cache and release the lock so that others can now access it.
Here is a brief example:
String key = "123";
Foo val = new Foo();
cache.acquireWriteLockOnKey(key);
try {
cache.put(new Element(key, val));
} finally {
cache.releaseWriteLockOnKey(key);
}
...sometime later
String key = "123";
cache.acquireWriteLockOnKey(key);
try {
Object cachedVal = cache.get(key).getValue();
cachedVal.setSomething("abc");
cache.put(new Element(key, cachedVal));
} finally {
cache.releaseWriteLockOnKey(key);
}
A READ lock does not prevent other READers from also acquiring a READ lock and reading. A READ lock cannot be obtained if there is an outstanding WRITE lock - it will queue.
A WRITE lock cannot be obtained while there are outstanding READ locks - it will queue.
In each case to avoid locking problems, the lock should be released after use. The lock release should be in a prefinally/pre block.
If before each read, you acquire a READ lock and then before each write you acquire a WRITE lock, then an isolation level akin to READ_COMMITTED is achieved.
The Explicit Locking API is in the ehcache-explicitlocking module. Download here.
This feature currently only works with Terracotta Server Array. It needs ehcache-core and ehcache-terracotta. which can be downloaded here.
The open source Terracotta Server Array kit (which includes ehcache-core and ehcache-terracotta) can be downloaded here.
