Search code examples
javaimplementationmutableweak-references

Java: Looking for mutable/re-referenceable weak reference implementation


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

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

I need this to avoid object creation which, in my case slows down the execution time by an order of magnitude, because I am constantly changing the object to which my weak reference refers.

I tried to copy the code from JDK, but it seems impossible since java.lang.ref.Reference uses the sun.misc.Cleaner class which is internal. I also looked on Android implementation but it seems it depends on Dalvik VM for Garbage collection. I wonder if this is actually possible to implement without changing the JVM / environment.


Solution

  • Wouldn't it just be possible to encapsulate your references 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 is actually possible to implement without changing the JVM / environment.

    No, you probably can't "reimplement" the WeakReference. It is a JVM-supported class.

    Are you sure it is the creation of WeakReference instances that slows it down? I wouldn't think doing

    ref = new WeakReference(someObject);
    

    instead of some

    ref.set(anotherObject);
    

    would be that much more expensive.