最近我开始使用 JCS,但遇到了“JCS 线程安全吗?”的问题。好吧,我查看了源代码,发现实现已经考虑了线程安全。
JCS.getInstance(String region) 总是为每个区域键返回相同的 CompositeCache 对象,包装在一个新的 JCS 对象中。换句话说,一个唯一的 CompositeCache 对象的引用保存在一个新创建的包装 JCS 对象中。当我们调用 JCS.get()、JCS.put()、JCS.remove() 等方法时,它总是会调用一个唯一的 CompositeCache 对象的方法。所以,它是单例的。
重要的是,CompositeCache 对象具有用于其写入操作(put remove 等)的同步方法,并且在内部实现中使用了 Hashtable 对象,它们也是线程安全的。所以我认为 JCS 已经在原子级别处理了线程安全。
What Thomas has mentioned above is true. If the cache object was synchronized, then a concurrency issue should have been avoided, which seems to be not the case as mentioned above, may be the issue is something else not really concurrency.
However, I just wanted to share the fact that, one should not plan to use the JCS by gaining an object level lock as discussed above, as the implementation seems to be thread safe, and we should let the concurrency to be handled at more atomic levels, looking for better performance.