0

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

Maurice
  • 6,698
  • 9
  • 47
  • 104
  • 2
    Even if you did so, you have no guarantees that the GC will ever run. I would not recommend doing that shutdown there. – Edwin Dalorzo Jan 17 '20 at 20:40
  • 6
    "*How do i override the finalize() method of the class object itself? Is this even possible?*" - No. No it is not. Even if it were, [`Object::finalize` is deprecated since Java 9](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Object.html#finalize()): "*The finalization mechanism is inherently problematic. Finalization can lead to performance issues, deadlocks, and hangs*". Just don't do it. – Turing85 Jan 17 '20 at 20:41
  • 2
    It's worth noting that a `Class` isn't eligible for collection until its `ClassLoader` also is. – Tom Hawtin - tackline Jan 17 '20 at 20:45
  • ok so is there another way to achieve this then? – Maurice Jan 17 '20 at 21:43
  • There is nothing about garbage collection that will interrupt running jobs or cause them not to finish. What actual problem are you trying to solve? – user207421 Jan 18 '20 at 01:27

1 Answers1

0

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

    }
}
ZakiMak
  • 2,072
  • 2
  • 17
  • 26