The question I asked myself a couple of times before I got around it was: What is the benefit of using caches and implement their overhead instead of using the much lighter and in some cases the faster hashmaps. It looked odd to me that I would be the only one with this question because of the widely used variety of caches. This fenomena did not occur to me like a fashion statement. I digged a bit in to it and try to explain here some very good reasons to use caches to prohibited some issues you might find.
The first thing you have to think about is the fact that the most of us work in a multi threaded environment. Not all the maps are threadsave. The only threadsave map is the concurentHashMap which inherits from the ConcurentMap Interface. Because of the thread safety these kind of maps will give a bit of overhead.
What I just wrote you might consider to use the ConcurentMap. Using a map might put you in the temptation of using it static, This should be the last thing on your mind static collections are a well known source of memory leaks. The problem with this is that: They stay in the classloader. They are not an instance. This means that they only will be removed until the classloader is removed. Most of the time this happens when the application dies. The donwside of this way of caching is that your application might run out of memory and crashes. A sign that might trigger you is the fact that you get an OutOfMemoryError. With maps instead of caches you are bound to keep track of what objects in your home made cache still have usefull references or not. Otherwise the garbage collector is not triggered to collect them. The reference that it will keep in Memory is the fact that the most Maps do not use weak references.
Concurrency of caches is a very important point. But it is not the only one. If you are aware of the fact that you load huge amounts of data which might endangers the given memory to the jvm. To prevent this the most caches have parameters that can be set to use memory until a certain amount. After these values the caches will start serializing the data to disk for swap purposes.
The third point I like to raise is the fact: that all the maps are using strong references for their keys and values in stead of weak references. The only exception on this rule is the WeakHashMap. The downside of this map is that it is not natural threadsave.
If you are about to load a great amount of data which is pretty much static in the way it is not edited, but used for lookup. Using a Concurrent hashmap might be the right solution. But even then, be carefull using it with the Java keyword static.
Geen opmerkingen:
Een reactie posten