简体   繁体   English

Java终结器:可接受的用例?

[英]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.

相关问题 是否有与可编写脚本的Java小程序等效的.Net技术? (针对特定用例) - Is there a .Net technology equivalent to scriptable Java applets? (for a specific use-case) Java 8中Spliterator的一个很好的用例场景是什么? - What would be a good use-case scenario for the Spliterator in Java 8? 如何在cameraX中解除单个用例的绑定 - How to unbind single use-case in cameraX 私有接口方法,示例用例? - Private interface methods, example use-case? synchronized的用例(new Object()) - A use-case for synchronized(new Object()) 如何根据用例从Java加载本机库? - How do I load a native library from Java depending on the use-case? 这是使用JSP scriptlet的可接受的案例吗? - Is this an acceptable case to use a JSP scriptlet? 如何处理节点共享多个BNO的用例 - how to handle a use-case where a node is sharing multiple BNO 使用具有特定用例的 Spring 安全性获取访问令牌 - Get access token using Spring Security with a specific use-case 有关Java中的终结器的问题 - Question regarding finalizers in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM