简体   繁体   中英

Simple Java hash map with weak keys based on identity in Google Guava?

I need a simple hash map with weak keys. Java's own WeakHashMap gives me that, but not with identity semantics (it uses equals() for key comparison).

Google's Guava library has revamped its hash map methods. In the latest version (14.0), instead of using a MapMaker (which has many if not most things deprecated), I apparently should now use a CacheBuilder , which all sorts of options. Fine, it has a weakKeys() option, so that's what I'll use. But the resulting cache is also concurrent (ie it keeps various maps inside and uses its own internal set of keys to regulate access concurrently), and I can't turn that off; I don't need concurrency, as I'm already using my own ReadWriteLock to govern access to my map.

Fine, I'll accept concurrency; just give me the map! I try:

Map<Foo, Bar> map = CacheBuilder.newBuilder().weakKeys().build();

Wait, that gives me back a Cache<Object, Object> , which isn't a Map<Foo, Bar> ! How can I get a simple identity-based weakly-keyed map in Google Guava?

Assuming you're willing to live with concurrency, you're almost there:

CacheBuilder.newBuilder().weakKeys().build().asMap();

But that said...your use case isn't entirely clear, that is, why you need a map with these properties, and why you need a map with identity semantics when the keys have another notion of equality.

I need a simple hash map with weak keys.

I don't follow why you want to switch from MapMaker to CacheBuilder then. It sounds like what you want is what MapMaker is there for.

You may not think you need concurrency, but remember that GC can run concurrently, and cause stale entries to be cleaned up. Anyway, the concurrency won't even cost you much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM