Code example for ReferenceQueue

Methods: pollremove

0
			protected void finalize() { 
				finalized = true;
			} 
		} 
 
		final ReferenceQueue rq = new ReferenceQueue();
 
		class TestThread extends Thread {
			public void run() { 
				// Create the object in a separate thread to ensure it will be 
				// gc'ed 
				Object testObj = new TestObject();
				wr = new WeakReference(testObj, rq);
				testObj = null;
			} 
		} 
 
		Reference ref;
 
                Thread t = new TestThread();
                t.start();
                t.join();
                System.gc();
                System.runFinalization();
                ref = rq.remove();
                assertTrue("Unexpected ref1", ref == wr);
                assertNotNull("Object not garbage collected1.", ref);
                assertNull("Object could not be reclaimed1.", wr.get());
 
                t = new TestThread();
                t.start();
                t.join();
                System.gc();
                System.runFinalization();
                ref = rq.poll();
                assertTrue("Unexpected ref2", ref == wr);
                assertNotNull("Object not garbage collected.", ref);
                assertNull("Object could not be reclaimed.", ref.get());
                // Reference wr so it does not get collected 
                assertNull("Object could not be reclaimed.", wr.get());