I've got a class which manages a cache of objects.
The cache is cleaned once an hour via ScheduledExecutorService
.
Is it ok to shutdown the ExecutorService
via the class finalize()
method?
@Override
protected void finalize() throws Throwable {
EXECUTOR_SERVICE.shutdownNow();
}
I'm currently running on Java 6.
There is no "call-this-last" method in Java.
The finalize
method is actually a "eat-memory-and-maybe-don't-even-call-me" method in Java.
The ExecutorService has shutdown
and a shutdownNow
.
Use these,
but not in a finalize
method.
Call shutdown
when your app knows that it "wants to stop soonish".
Call shutdownNow
when your app knows that it "wants to stop asap, but maybe not immediately`.
There is no way to instruct the ExecutorService
to "stop now, don't wait".
Here is a Brief ExecutorService Tutorial on Baeldung.