How to create a WeakHashSet / WeakSet in Java

1

The java.lang.ref package provides classes that model reference types in Java, such as Reference, SoftReferece, WeakReference, and PhantomReference.

  

Still do not know these references in Java? See this question:    Canonicalized Mapping and WeakReference

One of the Java SE classes that uses WeakReference is the java.util.WeakHashMap , where we have key as a weak reference, ie even with reference it is collected in the next Garbase cycle Collector (if there is no other StrongReference).

  

"... WeakHashMap may behave as though an unknown thread is silently   removing entries. "

Javadocs Source: link

Interestingly, we do not have a Set implementation with this semantics - WeakSet, at least not on the Java SE platform.

How can we get an instance of WeakSet?

    
asked by anonymous 27.06.2015 / 23:05

1 answer

1

To create a WeakHashSet, simply use the following method:

Set<Object> weakHashSet = Collections.newSetFromMap(
        new WeakHashMap<Object, Boolean>());

Interestingly, the Collections class is a class with many incredible methods, I recommend everyone who knows their methods, for example, if we want a synchronized version of WeakHashMap, but do it as follows:

Collections.synchronizedMap(aWeakHashMap);

What the above method does is decorate the behavior of WeakHashMap by synchronizing all of its methods. We can use this method to decorate any other Map

Source: link

    
27.06.2015 / 23:05