简体   繁体   中英

How do i override the finalize() method of the class object itself?

My problem is straightforward. I have a class that has a static ThreadPoolExecutor object. This threadpoolexecutor object is thus shared by all the instances of the class. If i were to shut the entire application down the shared class object would be garbage collected. I would like the threadpoolexecutor to be able to finish its pending jobs by calling shutdown on it and awaitTermination after that. This should be done in the finalize() method of the class object itself. My question is: How do i override the finalize() method of the class object itself? Is this even possible?

Thank you

finalize() is really not recommended as it's not reliable. However, you could benefit from using JVM ShutdownHooks . Access your static pool inside the hook and attempt to do your cleanup.

Example Usage:

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();
        }));

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM