是有java.concurrent.util(或等效)为WeakHashMap? [英] is there java.concurrent.util (or equivalent) for WeakHashMap?

查看:186
本文介绍了是有java.concurrent.util(或等效)为WeakHashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码可以使用 Collections.synchronizedMap()重写,但是仍然保持并发的正确性?

  Collections.synchronizedMap(new WeakHashMap< Class,Object>()); 

是否有来自java.util.concurrent的东西可以改用?注意,只需用

  new ConcurrentHashMap< Class,Object>(new WeakHashMap< Class,Object> 

显然不会工作

解决方案

Guava CacheBuilder 类允许

  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 using Class instances but is a potential pitfall.

这篇关于是有java.concurrent.util(或等效)为WeakHashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆