Question

In a program, I am planning to use singleton hashmap, being generated in Spring IoC, as shared resourced in between different threads, but I need to make sure that this instance is not going to be regenerated ever, otherwise, I lose my cached data. Can I rely on it?

default-lazy-init="true"

<util:map id="sharedResource" map-class="java.util.HashMap" key-type="KeyClass" value-type="ValueClass"/>
Was it helpful?

Solution

Spring beans are singletons by default, so you are good. However, there thread safety is not guaranteed for the Hashmap used by two or more threads. You can overcome this by using ConcurrentHashMap as the map-class.

Having said that, I think this is a rudimentary caching strategy in my opinion. If it serves your purpose, then it is great. If you need more sophisticated caching strategies, suggest looking into Ehcache or Memchached.

OTHER TIPS

This generates a singleton instance per spring application context. You also need to make sure that all your modules share the same spring context. If another module loads its own context, you get a whole new copy of all the instances in the file, including the singleton ones.

Make sure you have a centralized place to generate and manage the life-cycle of the spring context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top