tags:

views:

237

answers:

3

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?

+5  A: 

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.

Andreas Petersson
This MapMaker is something new to me. I must take a look at it. Thanks for the tip!
Henrik Paul
+8  A: 

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

David Rabinowitz
So, assuming I have a one-VM application that can fit all the data I ever want in the cache at once, would you say that ready implementations have added benefits? Naturally, once there's more VMs, or I can't fit all the data at once in the cache, there's good reason to not reinvent the wheel.
Henrik Paul
As with many things, it sounds like the implementers of existing cache libraries have just thought through a lot of the issues you will run into. You should probably at least read the descriptions for each so that when a problem comes up in coding your cache you will readily recognize them and at least one potential solution.
Bill K
+3  A: 

"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.

Boris Pavlović