4

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?

shinzou
  • 5,850
  • 10
  • 60
  • 124
  • 2
    Possible duplicate of [How to shutdown an ExecutorService?](http://stackoverflow.com/questions/10504172/how-to-shutdown-an-executorservice) – Nicolas Filotto Sep 13 '16 at 19:44
  • Examine a thread dump (or use a tool like visualvm) after you try to quit and see what is still running. – Rob Sep 13 '16 at 19:44
  • @NicolasFilotto it's not the service that I can't shut down, it's the `newSingleThreadExecutor`. – shinzou Sep 13 '16 at 19:52
  • it's the same thing, it is simply a specific use case of what you have in the duplicate answer – Nicolas Filotto Sep 13 '16 at 20:36
  • I'd do a thread-dump to figure out what non-deamon threads are actually left running – Gray Sep 14 '16 at 00:22

1 Answers1

3

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();
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32