Reputation: 67723
I'm doing a Java EE application, and I'm at a point where I've concluded that I need a cache for my objects.
My current requirements aren't much more complicated than some kind of key-value storage, possibly something that can handle a tree. It would be tempting to write a simple custom static/singleton class containing one or more maps. But, since there are several implementations that do more or less just like this (Memcached comes to mind), I began wondering that there must be some added value into using Memcached, instead of just my own implementation.
So, I'm asking for thoughts about this: why should I pick up a ready-made cache, when I can do my own static data? And vice versa; why should I write a static class, when I can pick up a ready-made cache?
Upvotes: 6
Views: 1200
Reputation: 16518
For many cases of complex object graphs I had good-enough performance with a one-liner
new MapMaker().weakKeys().makeMap();
This creates a map using Google collections, with can be used as a cache for complex objects.
Since the keys are weak, and eventually go out of scope, it is unlikely that this will cause memory issues.
So I'd say for simple cases - don't bother with the "cognitive load" of a distributed cache. Serialisation issues, latency etc.. you will not want to handle those.
Upvotes: 6
Reputation: 64640
"Why should I write a static class, when I can pick up a ready-made cache?"
When you don't want to include third-party dependencies in your project and there's no better way to learn how to write caches.
Upvotes: 3
Reputation: 30448
There are many cache implementations, both open source and commercial. There are many issues regarding writing a correct cache - time to leave of the objects, eviction policies, persistence, memory management, and more, so I wouldn't start one of my own (why to reinvent the wheel?)
Take a look at one of the following implementations:
See more at http://java-source.net/open-source/cache-solutions
Upvotes: 9