Pregunta

I have a controller class that, in the course of its operation, uses an executor it maintains to perform tasks. If I just let the gc clean up the controller when it goes out of scope, the JVM doesn't seem to die. I'm assuming that this is because the default executor doesn't time out, or times out after a long while.

Given that the executor should never be shutdown while the controller is still accessible, and that the executor will not be used after the controller is garbage-collected, would it be an safe/acceptable use of a finalizer to use:

@Override public void finalize() { executor.shutdown(); }

I ask because every discussion about finalizers seems to boil down to, "do not use unless very specific circumstances that I'm not going to elaborate on."

¿Fue útil?

Solución

The reason the executor doesn't die is that the thread isn't a daemon thread, so it keeps the JVM alive. See Thread.setDaemon(boolean).

This isn't a good time to use a finalizer. Finalizers should only be used to clean up native resources (eg resources accessed via JNI).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top