JavaFX Task sample using Java8 CompletableFuture

After reading Java8 Concurrency articleJava技術最前線 - 詳解 Java SE 8 第19回 Concurrency Utilitiesのアップデート その1:ITpro by @,
I wanted to try how to use JavaFX Task with CompletableFuture.

This is very easy thanks to this website. 1 Concurrency in JavaFX (Release 8)

  • code1(FXMLDocumentController.java)

This code shows you how to control these tasks.

public class FXMLDocumentController implements Initializable {
    @FXML
    private ProgressBar progressbarA;
    @FXML
    private ProgressBar progressbarB;
    @FXML
    private ProgressBar progressbarC;    
    @FXML
    private void startTask(ActionEvent event){
        TaskSample taskA = new TaskSample();
        this.progressbarA.progressProperty().bind(taskA.progressProperty());
        TaskSample taskB = new TaskSample();
        this.progressbarB.progressProperty().bind(taskB.progressProperty());
        TaskSample taskC = new TaskSample();
        this.progressbarC.setProgress(0);
        taskC.setOnRunning(e -> {
            this.progressbarC.progressProperty().bind(taskC.progressProperty());
        });
        // just use CompletableFuture for executing tasks
        CompletableFuture<Void> futureA = CompletableFuture.runAsync(taskA);
        CompletableFuture<Void> futureB = CompletableFuture.runAsync(taskB);
        futureA.runAfterBoth(futureB, taskC);
    }
}
  • code2(TaskSample.java)

You just need to extend javafx.concurrent.Task for your own tasks.

public class TaskSample extends Task<Void>{
    @Override
    protected Void call() throws Exception {
        updateProgress(0, 10);
        IntStream.rangeClosed(1, 10).forEach(i -> {
            try {
                TimeUnit.SECONDS.sleep(1); // to do something
            } catch (InterruptedException ex) {
                Logger.getLogger(TaskSample.class.getName()).log(Level.SEVERE, null, ex);
            }
            updateProgress(i, 10);
        });
        return null;
    }
}

The whole code is hereGitHub - tomoTaka01/ConcurrencyTaskSample: JavaFX Task sample using Java8 CompletableFuture
keep coding... ;-)