Skip to content

Instantly share code, notes, and snippets.

@bangarharshit
Created December 22, 2017 11:01
Show Gist options
  • Save bangarharshit/26e2685adc92e04c5c28ee6da5ed6d04 to your computer and use it in GitHub Desktop.
Save bangarharshit/26e2685adc92e04c5c28ee6da5ed6d04 to your computer and use it in GitHub Desktop.
Code to show that multiple calls to Weakreference.get() might return null.
// 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 { }
}
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