coder
coder

Reputation: 241

When to use Ehcache and Hash map for caching data?

I have class in which there is main method defined. When I run this class, it loads accounts data from account table and populates a global variable in my main class. Now the requirement in my project is, it is possible to update account table on fly. To handle this i subscribe to last updated timestamp on account table and use it to check if the data in the hashtable is up to date.

Is it advisable to use hashMap here ? Isnt using ehcache or hashmap in my main program one and the same. Both occupy same space in my JVM. I am trying to understand when to use hashMap in java program and when to use Ehcache

Upvotes: 5

Views: 4553

Answers (2)

Henri
Henri

Reputation: 5731

A HashMap is not concurrent. So you can't update it. A ConcurrentHashMap is. So you want that.

Ehcache (on-heap) is a ConcurrentHashMap with expiration and eviction handling.

It is also JSR107 compliant so it makes it easier to have transparent caching with many frameworks.

But if you know how many elements there will be in your map. And you know they never expire unless you replace them, then a ConcurrentHashMap will do what you need.

Bottom line, Ehcache is an enhanced ConcurrentHashMap.

Upvotes: 5

cocsackie
cocsackie

Reputation: 66

Use EhCache, because it can work like a HashMap, while having a possibility to change it's configuration.

While the dataset is small it might be feasible to load it entirely into memory (HashMap), otherwise you have to decide how much memory you want to allocate for it, and you have to keep some for other things.

This is where EhCache comes in handy:

  • configurable size (in cache entries)
  • keeps "the most useful" entries in it (depending on algorithm used)
  • might store some entries on disk
  • supports TTL (Time To Live), TTI (Idle), same for disk, basically if entries aren't used, cache does not take any space
  • supports clustering
  • good for bigger apps
  • etc.

While HashMap:

  • Keeps everything in memory
  • Can be simple to use
  • Ok for simple programs

Sometimes caches contain data that is not up to date (either bug or DB manipulated without application knowledge). Without cleanup mechanism HashMap will keep that data. While EhCache has a chance (TTL, TTI) to remove it and load up to date data when necessary.

Upvotes: 3

Related Questions