Java direct memory: using sun. Com in custom classes misc. Cleaner

In Java, the memory allocated by NiO direct buffer is the same as sun misc. Cleaner instances are released together, and some special phantom references are more effective than object finalization

Is this cleaner mechanism hard coded in the JVM only in direct buffer subclasses, or can cleaners be used in custom components (such as writing custom direct byte buffers)?

Here, I'm not talking about retrieving cleaner fields from an existing NiO direct buffer I'm not talking about freeing memory manually This is about writing a new class to allocate direct memory and efficient automatic cleaning through the garbage collector mechanism

Solution

Spend more time reading API documentation( http://docs.oracle.com/javase/7/docs/api/java/lang/ref/package-summary.html )After that, I think I have a more detailed answer:

1) You can reuse sun misc. Cleaner to perform efficient cleaning of its own custom classes You declare the cleaner by calling the factory method provided:

sun.misc.Cleaner.create(Object ob,Runnable cleanup);

For a while, I couldn't make it work because I was stupid enough to define my cleaner's executable cleaning code as an anonymous class. It kept (strong) referring to my instruction object and prevented it from being "reached by the phantom"

2) There is no other way to achieve this effective cleanup (not even with the help of phantom reference)

In fact, the reference handler thread handles sun in a special way misc. Instance of Cleaner:

// Fast path for cleaners
if (r instanceof Cleaner) {
    ((Cleaner)r).clean();
    continue;
}

This means that the cleanup code is called directly from the reference handler thread, while in standard use, the reference must be queued by the reference handler thread and then dequeued and processed by another application thread

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>