[英]Java finalizers: An acceptable use-case?
I have a controller class that, in the course of its operation, uses an executor it maintains to perform tasks. 我有一个控制器类,在其操作过程中,使用它维护的执行程序来执行任务。 If I just let the gc clean up the controller when it goes out of scope, the JVM doesn't seem to die. 如果我只是让gc在超出范围时清理控制器,那么JVM似乎不会死。 I'm assuming that this is because the default executor doesn't time out, or times out after a long while. 我假设这是因为默认执行程序不会超时,或者会在一段时间后超时。
Given that the executor should never be shutdown while the controller is still accessible, and that the executor will not be used after the controller is garbage-collected, would it be an safe/acceptable use of a finalizer to use: 鉴于在控制器仍可访问时永远不要关闭执行器,并且在控制器被垃圾回收之后将不再使用该执行器,因此使用终结器是安全/可接受的:
@Override public void finalize() { executor.shutdown(); }
I ask because every discussion about finalizers seems to boil down to, "do not use unless very specific circumstances that I'm not going to elaborate on." 我之所以这样问,是因为每次有关终结器的讨论都可以归结为: “除非我不打算阐述非常具体的情况,否则不要使用。”
The reason the executor doesn't die is that the thread isn't a daemon thread, so it keeps the JVM alive. 执行程序不死的原因是该线程不是守护程序线程,因此可以使JVM保持活动状态。 See Thread.setDaemon(boolean)
. 请参见Thread.setDaemon(boolean)
。
This isn't a good time to use a finalizer. 这不是使用终结器的好时机。 Finalizers should only be used to clean up native resources (eg resources accessed via JNI). 终结器仅应用于清理本机资源(例如,通过JNI访问的资源)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.