Java Reference
In-Depth Information
Listing4-9 showshowyoumightuse PhantomReference todetectthefinaliza-
tion of a large object.
Listing 4-9. Detecting a large object's finalization
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
class LargeObject
private byte[] memory = new byte[1024*1024*50]; // 50
class LargeObjectDemo
public static void main(String[] args)
ReferenceQueue<LargeObject> rq;
rq = new ReferenceQueue<LargeObject>();
PhantomReference<LargeObject> pr;
pr = new PhantomReference<LargeObject>(new LargeOb-
ject(), rq);
byte[] b = new byte[1024];
while (rq.poll() == null)
System.out.println("waiting for large object to be
b = new byte[b.length*10];
System.out.println("large object finalized");
System.out.println("pr.get() returns "+pr.get());
Listing 4-9 declares a LargeObject class whose private memory array occupies
50MB.IfyourJVMthrows OutOfMemoryError whenyourun LargeObject ,you
might need to reduce the array's size.
Search WWH ::

Custom Search