RFR 9: 8138696 : java.lang.ref.Cleaner - an easy to use alternative to finalization

Peter Levart peter.levart at gmail.com
Wed Oct 14 16:39:11 UTC 2015



On 10/14/2015 04:23 PM, Alan Bateman wrote:
>
> On 14/10/2015 15:03, Roger Riggs wrote:
>> Hi Alan,
>>
>> So any user of the Cleaner can take advantage of the mechanism, for 
>> example in a different package or module.
>> For example, Netbeans.
> Cleaner + Cleanable need to be public of course so maybe we should 
> wait for the examples that extend WeakCleanableRef or cast the 
> Cleanable to a WeakCleanableRef before seeing if this is the right 
> thing or not.
>
> -Alan

Hi Alan,

I think you are referring to Cleaner.WeakCleanable which is public and 
abstract right? Because Cleaner.WeakCleanableRef is private.

Besides being resource-friendly, a WeakCleanable is also a Reference, 
which means it has the get() method, so users can access the referent 
through it until the Reference is cleared. This can be useful in data 
structures where WeakCleanable can be subclassed to hold state that is 
needed to remove itself from the data structure and act as a 
[Weak|Soft]Reference so that it's referent is accessible through it. 
Imagine the following:

public class WeakKey<K> extends WeakCleanable {
     private final hash;
     private final ConcurrentHashMap<WeakKey<K>, ?> map;
     public WeakKey(K key, Cleaner c, ConcurrentHashMap<WeakKey<K>, ?> 
map) {
         super(key, c);
         this.hash = key.hashCode();
         this.map = map;
     }
     public int hashCode() { return hash; }
     public boolean equals(Object obj) {
         if (!(obj instanceof WeakKey)) return false;
         K key = get();
         if (key == null) return obj == this;
         return key == ((WeakKey<?>)obj).get();
     }
     @Override protected void performCleanup() {
         map.remove(this);
     }
}

...
ConcurrentHashMap<WeakKey<K>, Data> map = ...
Cleaner cleaner = ...
K key = ...
Data data = ...

map.put(new WeakKey<>(key, cleaner, map), data);


Voila, you have a  background-auto-cleaning ConcurrentWeakHashMap-like 
data structure.


Regards, Peter




More information about the core-libs-dev mailing list