I am writing a JavaFX application and my objects extend Task to provide concurrency away from the JavaFX GUI thread.
My Main class looks like this:
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent t) {
//I have put this in to solve the threading problem for now.
Platform.exit();
System.exit(0);
}
});
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
My GUI Controller Sample looks like this (abstracted slightly):
ExecutorService threadPool = Executors.newFixedThreadPool(2);
private void handleStartButtonAction(ActionEvent event) {
MyTask task = new MyTask();
threadPool.execute(task);
}
At the moment my task just does a sleep and prints numbers 1 through 10:
public class MyTask extends Task<String> {
@Override
protected String call() throws Exception {
updateProgress(0.1, 10);
for (int i=0;i<=10;i++) {
if (isCancelled()) {
break;
}
Thread.sleep(1000);
System.out.println(i);
updateProgress(i, 10);
}
return "Complete";
}
}
The problem I have is once the task completes it appears as though the thread the task is launched with continues to run. So when I exit the JavaFX application by pressing the "X" top right corner, the JVM continues to run and my application does not terminate. If you look at my main class, I have put in System.exit() which seems to solve the problem though I am aware this is not the correct way.
Can someone suggest what I need to do in terms of terminating my child threads, and what is the accepted way of doing this? i.e, checking they are complete and then terminated for example.
Thanks