Java: search for mutable / re-referenced weak reference implementation

I am looking for a weak reference implementation similar java.lang.ref.WeakReference, but which offers a method set()or some other way to reassign the created weak reference object. Here is an example:

MutableWeakReference ref = new MutableWeakReference(someObject);
ref.set(anotherObject);

I need this to avoid creating an object, which in my case slows down the execution time by an order of magnitude, because I constantly change the object to which my weak link refers.

I tried to copy the code from the JDK, but this seems impossible because it java.lang.ref.Referenceuses a class sun.misc.Cleanerthat is internal. I also looked at the Android implementation, but it seems to depend on the Dalvik VM for garbage collection. I wonder if this is really possible to implement without changing the JVM / environment.

+5
source share
3 answers

It would not be easy to encapsulate your links in a simple

class MyOwnReference<T> {
    public T ref;
    public void set(T o) { ref = o; }
}

and create WeakReference<MyOwnReference<WhatEver>>?

I wonder if this can really be implemented without changing the JVM / environment.

No, you probably can't override WeakReference. This is a class supported by the JVM.

Are you sure instantiation WeakReferenceslows it down? I would not think to do

ref = new WeakReference(someObject);

instead of some

ref.set(anotherObject);

will be much more expensive.

+3
source

I am actually implementing an iterator. Whenever I move on to the next record, I need to create a new one WeakReference.

, WeakReference . WeakReference . , . , / () , .

, , 8-10 .

, , WeakReference .

- , ?

+3

. "" , JVM .

class MutableWeakReference<T> 

    WeakReference<T> wr;

    void set(T obj)
        wr = new WeakReference(obj);  
0

All Articles