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

后端 未结 3 1580
说谎
说谎 2021-02-13 09:04

In Java the memory allocated by NIO direct buffers is freed with sun.misc.Cleaner instances, some special phantom references that are more efficient than object fin

3条回答
  •  [愿得一人]
    2021-02-13 09:44

    If you rely on anything in a sun.misc package, you run the risk of it disappearing and breaking your code. Some pieces are more stable than others, but it's often a bad idea (devil's advocate: a lot of the methods in sun.misc.Unsafe are actually implemented by JVM intrinsics, making them faster than user-written JNI code).

    In this case, I think it's a bad idea: Cleaner is one possible implementation of cleanup via PhantomReference. There are others; Google for examples. For that matter, you could look at the source code of Cleaner itself as an example of how to use phantom references.

    You will need some sort of cleanup handler if you're going to have on-heap objects that refer to off-heap objects. Otherwise you'll create a true memory leak when those on-heap objects get collected.

提交回复
热议问题