When to use Java Cache and how is it different from HashMap?

I went through javax.cache.Cache to understand its usage and behavior. He stated that

JCache is a map-like data structure that provides temporary storage of application data.

JCache and HashMap store items in Heap local memory and do not have persistence behavior by default. By implementing custom CacheLoader and CacheWriter , we can achieve perseverance. Also, when to use it?

+8
java hashmap caching jcache
source share
3 answers

Caches usually have more control logic than a map, which is nothing more than a more or less simple data structure.

Some concepts JCaches can implement

  • Expiration: Records can expire and be deleted from the cache after a certain period of time or after the last use
  • Eviction: items are removed from the cache if space is limited. There may be different eviction strategies for .e. LRU, FIFO, ...
  • Distribution: i.e. in a cluster while Maps are local to the JVM
  • Persistence: items in the cache can be persistent and present after a reboot, the contents of the card are simply lost
  • Additional memory: the cache implementation can use more memory than the JVM Heap provides, using the BigMemory technique, where objects are serialized into a separately distributed byte buffer. This JVM-external memory is controlled by the OS (paging), not the JVM
  • to store keys and values โ€‹โ€‹either by value or by reference (on the cards you can handle this yourself)
  • security application

Some of them are more general concepts of JCache, some of them are specific implementation details of cache providers.

+7
source share

Here are five major differences between both objects.

Unlike java.util.Map, Cache:

  • Do not allow null keys or values. Attempting to use null will throw java.lang.NullPointerException
  • provide the ability to read values โ€‹โ€‹from javax.cache.integration.CacheLoader (read-caching) when the requested value is not in the cache
  • provide the ability to write values โ€‹โ€‹to javax.cache.integration.CacheWriter (end-to-end caching) when a value is created / updated / deleted from the cache
  • provide an opportunity to monitor changes in the cache entry
  • can record and measure operational statistics.

Source: GrepCode.com

+1
source share

In most cases, caching implementations store these cached objects out of the heap (out of GC reach). GC keeps track of every object hosted in Java. Imagine you have millions of objects in memory. Believe me, if these objects are not so complicated, the performance of your application will be terrible.

0
source share

All Articles