JavaFx savely stopping Background Task
<p>right now I have a JavaFx program using a JavaFx Task inside a Thread as background process.</p>

<pre><code>Task&lt;Void&gt; task = new Task&lt;Void&gt;( ){
    @Override
    protected Void call() throws Exception {
        while(running){
            doSomething();
        }
        saveData();
        return null;
    }
};
Thread th = new Thread(task);
th.start();
</code></pre>

<p>I would like to stop this process as smoothly as possible (meaning I would like to stop the process by setting running = false; and thus call the save() method whenever possible. At the same time I want to make sure that the background process has no chance to keep running after the JavaFx process (the window) was closed.</p>

<p>At the moment I am setting the Thread as a Deamon to make sure the process dies after the JavaFx process is dead (the two processes are the only ones running)</p>

<pre><code>th.setDeamon(true);
</code></pre>

<p>At the same time I added a CloseRequestListener to my only Stage</p>

<pre><code>stage.setOnCloseRequest( e -&gt; running = false);
</code></pre>

<p>Now my Question:</p>

<p>Since the process is a Deamon, it can be removed in the middle of a run. Is there a better way to make sure the background task dies after the JavaFx process died? (even if the JavaFx process is forcefully killed)</p>

<p>Or is there a way to smoothly kill a deamon thread?</p>

<p>Edit: My main priority is that the background thread can't stay alive for itsself. And the second priority is that the background thread is killed as smoothly as possible.</p>