Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // we want to make sure that Service will not leak the Activity
- // because of the registered the anonymous callback
- public void test () throws InterruptedException {
- Service service = new Service();
- Activity activity = new Activity(service);
- activity.onStart();
- // store a PhantomReference to watch the lifecycle of listener
- ReferenceQueue<Activity.Listener> referenceQueue = new ReferenceQueue<Activity.Listener>();
- 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)
- activity.onStop();
- // reference = null; // uncomment to demonstrate why it's important to keep a strong reference to the PhantomReference
- activity = null; // at this point we removed the strong reference to our Activity,
- // service should not leak the Activity & Activity should be GC'd
- // trigger the collection of PhantomReference
- Runtime.getRuntime().gc();
- Reference<?> ref = referenceQueue.remove(TimeUnit.SECONDS.toMillis(10));
- assertNotNull(ref);
- ref.clear();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement