Hi, I want to code a simple cache in my java code to cache huge records being fetched from database so that i save upon accessing database everytime. I can't use any cache product so i have to code a simple one myself.
a few questions:
1. what i should choose between a hashmap & hashtable for keeping my data 2. should the cache class be a singlton class if yes - why? 3. Is there anything special i need to take care of other then refreshing cache
1. Use HashMap. Forget about Hashtable. Hashtable is a legacy collection class from Java 1.1. Don't use legacy collection classes like Hashtable and Vector in new Java code; use HashMap and ArrayList instead.
2. You'll want to have just one instance of the cache in your application, so making the cache class a singleton is an option, but it's not absolutely necessary.
3. If your application is multi-threaded, make sure that the cache is properly synchronized (so that different threads are not writing to and reading from the cache at the same time, for example).
Also, if your application is a J2EE application and it is clustered, then the analysis changes, because there would only be a singleton per JVM, and in a clustered application server environment, you'd have multidple JVMs.
This does not mean you have to scrap singletons, but you do have to keep it in mind when you design this.
"Per JVM" is almost true. In complex applications with multiple class loaders the truth is sometimes surprising: one instance perclass loader.
What makes Singleton work is a static variable referring to the single instance. If you have a non-singleton with a static variable referring to the Map, you get roughly the same effect.
I worked with a cache set up like this: The public API is on a class with all static methods, so clients simply code Cache.put(key,value) or Cache.get(key). Inside there is a static variable referring to an implementation class that has nothing static. The static methods just pass through to the non-static. Frinstance:
I was able to swap in different implementations - one with instrumentation for performance checking, one that deletes entries after a few seconds, one that deletes the oldest when size hits a limit. Clients never have to know which implementation is in effect.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com