Search code examples
javafxtaskexecutionsequential

Recommended way to run sequential background Tasks in JAVAFX in given order


Because of the way I modularized my code, I have several background (non-JAVAFX) Tasks that I wish to execute from my JAVAFX controller sequentially in a specified order. I would like the next Task to start as soon as possible after the previous Task finishes. I searched for examples, but I think they did not guarantee that the treads would be executed in the specified order. I also know that I generally should not try to make the FX thread wait or loop to check the progress of the task lest the GUI freeze. Being a beginner, I do not know how to implement my goal. Suppose I have these Task: task1, task2, task3. Any general recommendations on how to run task1, then task2, then task3?


Solution

  • Create a single-thread executor to execute the tasks:

    ExecutorService exec = Exectors.newSingleThreadExecutor();
    

    You probably want to scope this as an instance variable in the class that creates the tasks.

    Then just do:

    Task<Something> task1 = ... ;
    Task<Something> task2 = ... ;
    Task<Something> task3 = ... ;
    
    exec.submit(task1);
    exec.submit(task2);
    exec.submit(task3);