Ehcache(2.9.x) - API Developer Guide, Using Explicit Locking

About Explicit Locking

Ehcache contains an implementation which provides for explicit locking, using read and write locks.

With explicit locking, it is possible to get more control over Ehcache ‘s locking behavior to allow business logic to apply an atomic change with guaranteed ordering across one or more keys in one or more caches. It can therefore be used as a custom alternative to XA Transactions or Local transactions.

With that power comes a caution. It is possible to create deadlocks in your own business logic using this API.

Code Sample for Explicit Locking

The following is a simple example that shows how to use explicit locking.

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);
}

How Locking Works

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 the lock should be released after use to avoid locking problems. The lock release should be in a “finally” 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 Locking API

The following methods are available on Cache and Ehcache.

/**
* Acquires the proper read lock for a given cache key
*
* @param key - The key that retrieves a value that you want to protect via locking.
*/
public void acquireReadLockOnKey(Object key) {
   this.acquireLockOnKey(key, LockType.READ);
}
/**
* Acquires the proper write lock for a given cache key
*
* @param key - The key that retrieves a value that you want to protect via locking.
*/
public void acquireWriteLockOnKey(Object key) {
   this.acquireLockOnKey(key, LockType.WRITE);
}
/**
* Try to get a read lock on a given key. If can‘t get it in timeout millis
* then return a boolean telling that it didn‘t get the lock
*
* @param key - The key that retrieves a value that you want to protect via locking.
* @param timeout - millis until giveup on getting the lock
* @return whether the lock was awarded
* @throws InterruptedException
*/
public boolean tryReadLockOnKey(Object key, long timeout) throws InterruptedException {
   Sync s = getLockForKey(key);
   return s.tryLock(LockType.READ, timeout);
}
/**
* Try to get a write lock on a given key. If can‘t get it in timeout millis
* then return a boolean telling that it didn‘t get the lock
*
* @param key - The key that retrieves a value that you want to protect via locking.
* @param timeout - millis until giveup on getting the lock
* @return whether the lock was awarded
* @throws InterruptedException
*/
public boolean tryWriteLockOnKey(Object key, long timeout) throws InterruptedException {
   Sync s = getLockForKey(key);
   return s.tryLock(LockType.WRITE, timeout);
}
/**
* Release a held read lock for the passed in key
*
* @param key - The key that retrieves a value that you want to protect via locking.
*/
public void releaseReadLockOnKey(Object key) {
   releaseLockOnKey(key, LockType.READ);
}
/**
* Release a held write lock for the passed in key
*
* @param key - The key that retrieves a value that you want to protect via
* locking.
*/
public void releaseWriteLockOnKey(Object key) {
   releaseLockOnKey(key, LockType.WRITE);
}
/**
* Returns true if a read lock for the key is held by the current thread
*
* @param key
* @return true if a read lock for the key is held by the current thread
*/
boolean isReadLockedByCurrentThread(Object key);
/**
* Returns true if a write lock for the key is held by the current thread
*
* @param key
* @return true if a write lock for the key is held by the current thread
*/
boolean isWriteLockedByCurrentThread(Object key);

Supported Topologies

Except as noted in the The Locking API, the locking API supports the standalone and distributed cache topologies. It does not support the replicated topology.

时间: 2024-11-05 17:31:45

Ehcache(2.9.x) - API Developer Guide, Using Explicit Locking的相关文章

Ehcache(2.9.x) - API Developer Guide, Cache Eviction Algorithms

About Cache Eviction Algorithms A cache eviction algorithm is a way of deciding which element to evict when the cache is full. In Ehcache , the memory store and the off-heap store might be limited in size. When these stores get full, elements are evi

Ehcache(2.9.x) - API Developer Guide, Write-Through and Write-Behind Caches

About Write-Through and Write-Behind Caches Write-through caching is a caching pattern where writes to the cache cause writes to an underlying resource. The cache acts as a facade to the underlying resource. With this pattern, it often makes sense to

Ehcache(2.9.x) - API Developer Guide, Key Classes and Methods

About the Key Classes Ehcache consists of a CacheManager, which manages logical data sets represented as Caches. A Cache object contains Elements, which are essentially name-value pairs. You can use Cache objects to hold any kind of data that you wan

Ehcache(2.9.x) - API Developer Guide, Searching a Cache

About Searching The Search API allows you to execute arbitrarily complex queries against caches. The development of alternative indexes on values provides the ability for data to be looked up based on multiple criteria instead of just keys. Note: Ter

Ehcache(2.9.x) - API Developer Guide, Class Loading

About Class Loading Class loading, within the plethora of environments that Ehcache can be running, could be complex. But with Ehcache, all class loading is done in a standard way in one utility class: ClassLoaderUtil. Plugin Class Loading Ehcache al

Ehcache(2.9.x) - API Developer Guide, Cache Extensions

About Cache Extensions Cache extensions are a general-purpose mechanism to allow generic extensions to a cache. Cache extensions are tied into the cache lifecycle. For that reason, this interface has the lifecycle methods. Cache extensions are create

Ehcache(2.9.x) - API Developer Guide, Blocking and Self Populating Caches

About Blocking and Self-Populating Caches The net.sf.ehcache.constructs package contains some applied caching classes which use the core classes to solve everyday caching problems. Two of these are BlockingCache and SelfPopulatingCache. Blocking Cach

Ehcache(2.9.x) - API Developer Guide, Cache Exception Handlers

About Exception Handlers By default, most cache operations will propagate a runtime CacheException on failure. An interceptor, using a dynamic proxy, may be configured so that a CacheExceptionHandler can be configured to intercept Exceptions. Errors

Ehcache(2.9.x) - API Developer Guide, Cache Decorators

About Cache Decorators Ehcache uses the Ehcache interface, of which Cache is an implementation. It is possible and encouraged to create Ehcache decorators that are backed by a Cache instance, implement Ehcache and provide extra functionality. The Dec