Advertisement
Guest User

Untitled

a guest
Oct 10th, 2015
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. // we want to make sure that Service will not leak the Activity
  2. // because of the registered the anonymous callback
  3. public void test () throws InterruptedException {
  4. Service service = new Service();
  5. Activity activity = new Activity(service);
  6. activity.onStart();
  7.  
  8. // store a PhantomReference to watch the lifecycle of listener
  9. ReferenceQueue<Activity.Listener> referenceQueue = new ReferenceQueue<Activity.Listener>();
  10. PhantomReference<Activity.Listener> reference = new PhantomReference<Activity.Listener>(service.listener, referenceQueue); // no need to store this reference since it's a root object (in stack memory)
  11.  
  12. activity.onStop();
  13. // reference = null; // uncomment to demonstrate why it's important to keep a strong reference to the PhantomReference
  14. activity = null; // at this point we removed the strong reference to our Activity,
  15. // service should not leak the Activity & Activity should be GC'd
  16.  
  17. // trigger the collection of PhantomReference
  18. Runtime.getRuntime().gc();
  19.  
  20. Reference<?> ref = referenceQueue.remove(TimeUnit.SECONDS.toMillis(10));
  21. assertNotNull(ref);
  22. ref.clear();
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement