Skip to content

Instantly share code, notes, and snippets.

@theotherian
Last active January 1, 2016 22:19
Show Gist options
  • Save theotherian/8209190 to your computer and use it in GitHub Desktop.
Save theotherian/8209190 to your computer and use it in GitHub Desktop.
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