Last active
January 1, 2016 22:19
-
-
Save theotherian/8209190 to your computer and use it in GitHub Desktop.
Different reference types in Java can be confusing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
What does it mean? |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.ref.SoftReference; | |
public class SoftlyReferenced { | |
private SoftReference<Object> value = new SoftReference<Object>(new Object()); | |
public Object getValue() { | |
return value.get(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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