A Cache provides storage of data for later fast retrieval.
This Cache interface is based on {@link java.util.concurrent.ConcurrentMap} with some modifications forfast distributed performance.
A Cache does not allow null keys or values. Attempts to store a null value or to use a null key either in a get or put operation will result in a {@link NullPointerException}.
Caches use generics throughout providing a level of type safety akin to the collections package.
Cache implements {@link Iterable} for {@link Cache.Entry}, providing support for simplified iteration. However iteration should be used with caution. It is an O(n) operation and may be slow on large or distributed caches.
The Cache API also provides:
- read-through caching
- write-through caching
- cache loading
- cache listeners
- statistics
- lifecycle
- configuration
Though not visible in the Cache interface caches may be optionally transactional.
User programs may make use of caching annotations to interact with a cache.
A simple example of how to use a cache is:
String cacheName = "sampleCache"; CacheManager cacheManager = Caching.getCacheManager(); Cache<Integer, Date> cache = cacheManager.getCache(cacheName); if (cache == null) { cache = cacheManager.<Integer,Date>createCacheBuilder(cacheName).build(); } Date value1 = new Date(); Integer key = 1; cache.put(key, value1); Date value2 = cache.get(key);
Concurrency
Concurrency is described as if there exists a locking mechanism on each key. If a cache operation gets an exclusive lock on a key, then all subsequent operations on that key will block until that lock is released. The consequences are that operations performed by a thread happen-before read or mutation operations performed by another thread, including threads in different Java Virtual Machines.
@param < K> the type of keys maintained by this cache
@param < V> the type of cached values
@author Greg Luck
@author Yannis Cosmadopoulos
@since 1.0