kuhaku kuhaku - 2 months ago 8
Java Question

Executors or threads keep program from shutting down

In my program some threads are created and given a

Task
that ends (so that thread should die), and I also have a
Executors.newSingleThreadScheduledExecutor
and
Executors.newSingleThreadExecutor
, I noticed that if I press a close button that I made:

@FXML private void handleExit(){
gameManager.cleanup();
Stage stage = (Stage)menuBarTopMenu.getScene().getWindow();
Platform.exit();
stage.close();
}


I don't get the
Process finished with exit code 0
in intelij.

So I even set those threads I mentioned to daemons and this is the cleanup:

public void cleanup(){
updateTime.shutdown(); // it's Executors.newSingleThreadScheduledExecutor
updateTime.shutdownNow();
}


But I still don't see the successful exit. Could it be because I didn't shut down the
Executors.newSingleThreadExecutor
? I couldn't find a way to shut it down.

What other cleanup I should do?

Answer

Yup, it is exactly because you didn't call shutdown on newSingleThreadExecutor, but if you have other running threads they may also stop the app from quitting. To force VM to shutdown (all threads will be terminated) you can call System.exit(0);

you crate the Executor service as that:

ExecutorService service = Executors.newSingleThreadScheduledExecutor();

\\ use the service to do work
\\ to shutdown the service
service.shutdown();

\\ to wait till the service terminate
service.awaitTermination();
Comments