Monday, October 26, 2009

5 Hints You're Using A Map When You Should Be Using a Cache?

When developing software in Java one almost always ends up with a few maps that contain keyed data. Whether it's username -> conversational state, state code -> full state name, or cached data from a database. At what point do you move from a basic Map (or one of it's more fancy variants like LinkedHashMap subclasses or ConcurrentHashMap) to an open source, light weight cache like Ehcache?

Here are 5 quick things to look for:

5) You've built your own Map loader framework for bootstrapping and/or reads triggering loading
4) You need to be able to visualize and/or control your Map via JMX or a console. For example you want to watch the hit rate of your Map or track the size of your Map.

3) You're hacking in "overflow to disk" functionality and or persistence for your Map in order to handle memory pressure and/or restartability.

2) You're hacking in special behavior to cluster Maps when you scale out. This includes things like writing your own invalidation and/or replication solution over jms or RMI

1) You find yourself implementing your own eviction strategies.

Avoid The Slippery Slope:

It's a slippery slope. First you add in one feature, then another, and next thing you know you've reinvented the cache wheel. No point in doing that. There are great caches out there that are apache licensed, light weight and have the above features you need and more.

To learn more about Ehcache check it out at »


Kunal said...

notifications would be another one ..

Anonymous said...

I gotta admin, ehcache does not look light weight to me. Especially if you're only trying item 1), say making an LRU cache or one that expires items over a certain age (and all thread safely but fast, of course!)

The graphics on the front page are daunting, and even the getting started part of the manual make you feel that life is too short.

Steve Harris said...

Ignoring the website complexity ehcache core is about 256k and very simple to use. Check out the code snippets here to get started.

One can create a cache in a couple of lines of code and your going.

Anonymous said...

Okay, maybe not so bad if you ignore the configuration file jiggery-pokery and just create your memory caches in code.

Pity it isn't up to Java 5 yet, though. Generics really does help making cleaner and more robust code.

Steve Harris said...

Good point. The funny thing is that ehcache 1.6 and up require jdk 1.5. We should probably create an extended API (so we keep backward compatibility) that uses 1.5 and up constructs.

Steve Harris said...

Posted a JIRA here: