Releasing Memory Allocated by Native Libraries in Java

喜夏-厌秋 提交于 2019-11-30 14:42:24
Peter Lawrey

What you can do is use a Cleaner. This is a more official API in Java 9 but is available in Java 1.4+.

Essentially you give it a Runnable to execute when the resource is cleaned up.

One advantage of using a Cleaner is you can call it to clean up deterministically, but if you forget or fail to do so, the GC will call it after it runs.

There isn't a safe way to clean up an object when a thread dies as the Thread object can live for the life of the program even if dead. A simpler approach is to clean up as you know it is not needed or after the GC determines it is not required.

Another approach is to use a reference queue and a background thread. It's not as elegant but works across Java 8 and later versions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!