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.
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.
I am actually implementing an iterator of some kind. Whenever I advance to the next entry, I need to create a new
WeakReference
.
I'm puzzled why you would need to use a WeakReference
at all in an iterator. The normal use-case for WeakReference
is for long term references to objects. But an iterator is typically a short term object, and an iteration is typically a short term process. The fact that it / they use an ordinary (strong) reference to the target object in the short term shouldn't be a concern.
I have run some tests and it seems this is like 8-10 times slower.
Again, this suggests that you shouldn't be using a WeakReference
at all.
Is there a particular reason why won't a regular reference work for you?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With