[英]How do i override the finalize() method of the class object itself?
我的问题很简单。 我有一个具有静态ThreadPoolExecutor
对象的类。 因此,该线程池执行器对象由该类的所有实例共享。 如果我要关闭整个应用程序,共享类对象将被垃圾收集。 我希望 threadpoolexecutor 能够通过在其上调用shutdown
并在此之后awaitTermination
来完成其挂起的作业。 这应该在类对象本身的finalize()
方法中finalize()
。 我的问题是:如何覆盖类对象本身的finalize()
方法? 这甚至可能吗?
谢谢
finalize()
真的不推荐,因为它不可靠。 但是,您可以从使用JVM ShutdownHooks
受益。 访问钩子内的静态池并尝试进行清理。
示例用法:
public class ShutdownTest {
static PrintWriter writer = new PrintWriter(System.out);
public static void main(String[] args) throws InterruptedException {
writer.println("Application Started");
writer.flush();
Thread.sleep(2000);
Runtime.getRuntime().addShutdownHook(new Thread(() ->{
writer.println("Application shutdown started");
writer.println("Closing resource");
writer.close();
}));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.