• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Caching objects

 
Dennis Kopylenko
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am designing a way to cache objects which may or may not get persisted. The objects are tied to a user(id) and one user can have multiple objects floating around needing to be cached.

Is the best way to cache in memory is to just put the objects in a hash map or a more elegant utility has already been created for this...which takes care of many to many mapping, flushing the cache, etc.?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, welcome to the ranch!

A HashMap is usually pretty good for this.



Synchronization is a concern with multi-threaded systems. I usually just synchronize the get & put methods on the cache, keep the map completely private, never let anybody else see an iterator or keyset or valueset.
 
Dennis Kopylenko
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for replying, Stan.

I also happened to look at ehcache on sf and I was wondering what is the primary usecase for choosing ehcache over a custom solution?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With just a quick look at the ehcache front page it seems to have many nifty features that I would not try to write myself. If you need the distributed or disk backed features, pick it for sure. I plan to read up on it further to see if it would replace a chunk of a vendor framework we use.

Under the Do The Simplest Thing That Can Possibly Work (for now) principle, you might choose a simple hashmap to start. Hide the implementation well behind your own interface and you can swap in ehcache or another distributed cache later if you find you need the features.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic