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"/>
有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top