WeakHashMap是否有java.util.concurrent等价物? [英] Is there java.util.concurrent equivalent for WeakHashMap?

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

问题描述

是否可以使用 Collections.synchronizedMap()重写下面的代码片段,同时保持并发性的正确性?

Can the following piece of code be rewritten w/o using Collections.synchronizedMap() yet maintaining correctness at concurrency?

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

即。有什么来自java.util.concurrent可以使用吗?请注意,仅替换为

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>()));

显然不起作用

推荐答案

番石榴 CacheBuilder 类允许您轻松完成此任务。

Guava's CacheBuilder class allows you to do this easily.

CacheBuilder.newBuilder().weakKeys().build()

请注意,这会将键等同语义更改为 == 而不是 .equals()在您使用 Class 实例的情况下无关紧要,但这是一个潜在的陷阱。

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.

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

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