Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Java Cache and how it differs from HashMap?

I've gone through javax.cache.Cache to understand it's usage and behavior. It's stated that,

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

JCache and HashMap stores the elements in the local Heap memory and don't have persistence behavior by default. By implementing custom CacheLoader and CacheWriter we can achieve persistence. Other than that, When to use it?

like image 680
Kamal Chandraprakash Avatar asked Jun 08 '16 06:06

Kamal Chandraprakash


2 Answers

Caches usually have more management logic than a map, which are nothing else but a more or less simple datastructure.

Some concepts, JCaches may implement

  • Expiration: Entries may expire and get removed from the cache after a certain period of time or since last use
  • Eviction: elements get removed from the cache if space is limited. There can be different eviction strategies .e. LRU, FIFO, ...
  • Distribution: i.e. in a cluster, while Maps are local to a JVM
  • Persistence: Elements in the cache can be persistent and present after restart, contents of a Map are just lost
  • More Memory: Cache implementations may use more memory than the JVM Heap provides, using a technique called BigMemory where objects are serialized into a separately allocated bytebuffer. This JVM-external memory is managed by the OS (paging) and not the JVM
  • option to store keys and values either by value or by reference (in maps you to handle this yourself)
  • option to apply security

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

like image 88
Gerald Mücke Avatar answered Oct 18 '22 01:10

Gerald Mücke


Here are the five main differences between both objects.

Unlike java.util.Map, Cache :

  • do not allow null keys or values. Attempts to use null will result in a java.lang.NullPointerException
  • provide the ability to read values from a javax.cache.integration.CacheLoader (read-through-caching) when a value being requested is not in a cache
  • provide the ability to write values to a javax.cache.integration.CacheWriter (write-through-caching) when a value being created/updated/removed from a cache
  • provide the ability to observe cache entry changes
  • may capture and measure operational statistics

Source : GrepCode.com

like image 20
Yassin Hajaj Avatar answered Oct 18 '22 01:10

Yassin Hajaj