Created
December 22, 2017 11:01
-
-
Save bangarharshit/26e2685adc92e04c5c28ee6da5ed6d04 to your computer and use it in GitHub Desktop.
Code to show that multiple calls to Weakreference.get() might return null.
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
// GC is a background thread and JVM doesn't have a spec for it to be daemon or not. | |
// https://stackoverflow.com/questions/5553783/java-garbage-collection-thread-priority | |
public class WeakReferenceCaller { | |
public static void main(String[] args) throws InterruptedException { | |
MyObject myObject = new MyObject(); | |
Thread thread = new Thread(new WeakReferenceRunnable(myObject)); | |
thread.start(); | |
myObject = null; | |
System.out.println(myObject); | |
System.gc(); | |
while (true) { | |
Thread.sleep(200); | |
} | |
} | |
static class MyObject { } | |
} |
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
public class WeakReferenceRunnable implements Runnable { | |
private final WeakReference<Caller.MyObject> weakReference; | |
public WeakReferenceRunnable(Caller.MyObject input) { | |
this.weakReference = new WeakReference<Caller.MyObject>(input); | |
} | |
@Override public void run() { | |
while (weakReference.get() != null) { | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println("I am here"); // This will be printed. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment