Orange Receptacle
Orange Receptacle

Reputation: 1183

JavaFX: Running a Task in a separate thread doesn't allow anything else to run

I need constant data updating in my program, so I thought that through the use of JavaFX's Task that I would be able to have it run as a separate process in my program.

final Task task = new Task<Void>() {
    @Override
    protected Void call() throws Exception {
        Platform.runLater(() -> {
            while (true) {
                itemData.forEach(data -> {
                    System.out.println(data.getId());
                });
            }
        });
        return null;
    }
};
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();

This is declared in the initialize method provided by the Initializable interface.

When running this program, however, the task is the only thing that runs, even though the task is run on a separate thread. Why would it do this and not run like intended?

Upvotes: 1

Views: 1436

Answers (1)

fabian
fabian

Reputation: 82461

You're just starting a task only to use it to post a long running task on the UI thread. The Runnable

() -> {
    while (true) {
        itemData.forEach(data -> {
            System.out.println(data.getId());
        });
    }
}

still runs on the application thread, blocking it.

Only UI updates should be done on the application thread. The heavy work should be done on the other thread.

You should instead post only the updates on the application thread. Something like this:

@Override
protected Void call() throws Exception {
    while (true) {
        try {
            // add a pause between updates
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
        Platform.runLater(() -> itemData.forEach(data -> {
            System.out.println(data.getId());
        }));
    }
}

If you post updates too often, this can also make the application unresponsive.

Upvotes: 3

Related Questions