2

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.

LppEdd
  • 20,274
  • 11
  • 84
  • 139

2 Answers2

1

I recommend looking at the WeakReference class and it's use as a finalizer.

It is still dependent on the GC's reachability calculations which means it might not be called immediately, but it gets rid of the chance of zombie objects and a few other problems that plague the finalize pattern.

Bill K
  • 62,186
  • 18
  • 105
  • 157
1

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.

DwB
  • 37,124
  • 11
  • 56
  • 82