java Ehcache 和多线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/938926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ehcache & MultiThreading
提问by hakish
Does ehcache support multi-threading by default or does it require any configuration changes? On multi threading my application with Ehcache i found that the DB hit count is actually increasing i.e. there is no global cache available for all the threads despite the fact that my cache's are all Singletons. Any suggestions?
ehcache 是否默认支持多线程或是否需要任何配置更改?在使用 Ehcache 对我的应用程序进行多线程处理时,我发现 DB 命中计数实际上在增加,即尽管我的缓存都是单例,但没有可用于所有线程的全局缓存。有什么建议?
采纳答案by matt b
This may help answer your question, from the FAQ:
Is it thread safe to modify Element values after retrieval from a Cache?
Remember that a value in a cache element is globally accessible from multiple threads. It is inherently not thread safe to modify the value.It is safer to retrieve a value, delete the cache element and then reinsert the value.
从缓存中检索后修改元素值是否线程安全?
请记住,缓存元素中的值可以从多个线程全局访问。修改该值本质上不是线程安全的。检索值、删除缓存元素然后重新插入值更安全。
(emphasis added by me)
(重点是我加的)
回答by Audrius Meskauskas
From the official documentationappears it is specifically built and tested to run well under highly concurrent access, as long as you do not modify Elementfrom the multiple threads.
从官方文档看来,它是专门构建和测试的,可以在高并发访问下运行良好,只要不Element从多线程修改即可。
But, of course, this does not mean that using Ehcache makes other parts of your code thread safe. If you fetch the same value from multiple threads (using the same key), the instance may be shared and you need to know what you are doing before modifying it. Best seems to use immutable objects like strings as cached values.
但是,当然,这并不意味着使用 Ehcache 会使代码的其他部分线程安全。如果您从多个线程(使用相同的键)获取相同的值,则该实例可能会被共享,您需要在修改它之前知道自己在做什么。Best 似乎使用像字符串这样的不可变对象作为缓存值。

