我的问题很简单。我有一个具有静态ThreadPoolExecutor
对象的类。因此,该线程池执行器对象由类的所有实例共享。如果我要关闭整个应用程序,则共享类对象将被垃圾回收。我希望threadpoolexecutor能够通过在其上调用shutdown
并在其后调用awaitTermination
来完成其挂起的作业。这应该在类对象本身的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();
}));
}
}