Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of using ehcahce over a static HashMap

I have always used the java singleton class for my basic caching needs.
Now the project is using ehcache and without looking deeply into source code, I am not able to figure out what was wrong with the singleton pattern.

i.e What are the benefits of using the ehcahce framework except that the caching can be done by using xml configuration and annotation without writing the boilerplate code (i.e a static HashMap)

like image 504
Victor Avatar asked Aug 10 '12 19:08

Victor


3 Answers

It depends on what you need from your caching mechanism. Ehcache provides a lot of cool features, which require a lot of well designed code to do it manually:

  • LRU, LFU and FIFO cache eviction policies
  • Flexible configuration
  • Persistence
  • Replication
  • many more ...

I would recommend you go through them at http://ehcache.org/about/features and decide do you really need something in your project.

like image 150
udalmik Avatar answered Nov 10 '22 03:11

udalmik


The most important one:

The ability to overflow to disk - this is something you don't have in normal HashMap and writing something like that is far from trivial. EhCache can function as simple to configure key-value database.

Even if you don't use overflow to disk, there's a large boilerplate to write with your own implementation. If loading the whole database would be possible, that using memory database with persistence on write and restoring on startup would be the solution. But memory is limited and you have to remove the elements from memory. But which one, based on what? Also, you must assert cache elements are not too old. Older elements should be replaced. If you need to remove elements from cache, you should start from the outdated ones. But should you do it when user requests something? It will slow down the request. Or start your own thread?

With EhCache you have the library in which all those issues are addressed and tested.

like image 45
Danubian Sailor Avatar answered Nov 10 '22 02:11

Danubian Sailor


Also there is a clustered closed source version of ehcache, which allows you to have a distributed cache. That might be one reason you might want to consider using ehcache.

like image 21
Apurv Avatar answered Nov 10 '22 03:11

Apurv