本文介绍了是有java.concurrent.util(或等效)为WeakHashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码可以使用 Collections.synchronizedMap()
重写,但是仍然保持并发的正确性?
Collections.synchronizedMap(new WeakHashMap< Class,Object>());
是否有来自java.util.concurrent的东西可以改用?注意,只需用
new ConcurrentHashMap< Class,Object>(new WeakHashMap< Class,Object>
显然不会工作
解决方案
的类允许
CacheBuilder.newBuilder()。weakKeys()。build()
c $ c> .equals()这在您使用
$请注意,这会将键等同性语义更改为==
,而不是<$Class
实例时并不重要,但是是一个潜在的陷阱。Can the following piece of code be rewritten w/o using
Collections.synchronizedMap()
yet maintaining correctness at concurrency?Collections.synchronizedMap(new WeakHashMap<Class, Object>());
i.e. is there something from java.util.concurrent one can use instead? Note that merely replacing with
new ConcurrentHashMap<Class, Object>(new WeakHashMap<Class, Object>()));
obviously won't work
解决方案Guava's CacheBuilder class allows you to do this easily.
CacheBuilder.newBuilder().weakKeys().build()
Note that this changes key equality semantics to be
==
instead of.equals()
which will not matter in your case of usingClass
instances but is a potential pitfall.这篇关于是有java.concurrent.util(或等效)为WeakHashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!