How to create a Weakhashset /Weakset in Java

Asked

Viewed 67 times

1

The java.lang.ref package offers classes that model reference types in Java, such as Reference, Softreferece, Weakreference and Phantomreference.

Still not familiar with these references in Java? See this question: Canonicalized Mapping and Weakreference

One of the classes of Java SE using Weakreference is the java.util.WeakHashMap, where we have the key as weak reference, that is, even with reference the same is collected in the next cycle of the Garbase Collector (if there is no other Strongreference).

"...a Weakhashmap may behave as though an Unknown thread is Silently removing eccentries."

Fonte Javadocs: http://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html

Interestingly, we don’t have a Set implementation with this semantics - Weakset, at least not on the Java SE platform.

How then can we get a Weakset instance?

1 answer

1


To create a Weakhashset, just use the following method:

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

Interestingly, the Collections class, is a class with several incredible methods, I recommend to everyone who knows its 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 memorize the behavior of Weakhashmap, synchronizing all its methods. We can use this method to decorate any other Map

Source: http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#newSetFromMap%28java.util.Map%29

Browser other questions tagged

You are not signed in. Login or sign up in order to post.