Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Different reference types in Java can be confusing
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
public class PhantomlyReferenced {
private ReferenceQueue<Object> queue = new ReferenceQueue<>();
private PhantomReference<Object> value = new PhantomReference<Object>(new Object(), queue);
public Object getValue() {
// always returns null
return value.get();
}
}
import java.lang.ref.SoftReference;
public class SoftlyReferenced {
private SoftReference<Object> value = new SoftReference<Object>(new Object());
public Object getValue() {
return value.get();
}
}
import java.lang.ref.WeakReference;
public class WeaklyReferenced {
private WeakReference<Object> value = new WeakReference<Object>(new Object());
public Object getValue() {
return value.get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.