Search code examples
javaconcurrencysetguavaweak-references

Concurrent set with weak references and identity hash


I wanted a concurrent set with weak references to elements. I thought of doing this using Guava's MapMaker:

Set<Object> concurrentSet = Collections.newSetFromMap(
    new MapMaker<Object, Boolean>().weakKeys().makeMap());

Guava will automatically give you identity hashes with weak keys. However, it turns out that MapMaker does not allow type parameters.

file.java:123 type com.google.common.collect.MapMaker does not take parameters
                new MapMaker<Object, Boolean>().weakKeys().makeMap());
                            ^

Any solutions how I can obtain a concurrent set with weak references to elements?


Solution

  • As explained in the documentation, MapMaker is not a generic type; it's <Object, Object>. This means you can put anything as key or value, you just need to cast it when retreiving. Quoting the link:

       ConcurrentMap<Request, Stopwatch> timers = new MapMaker()
           .concurrencyLevel(4)
           .weakKeys()
           .makeMap();
    

    To get a Set with the Map entries, you just call Map#entrySet().