Hesk
Hesk

Reputation: 327

Non Javafx equivalent for Task

In a non-JavaFX application I would like to have the same Class like Task.

A Thread which executes something and is able to return its progress.

Is there something that could perform a task similar to the above mentioned?

Upvotes: 2

Views: 232

Answers (1)

James_D
James_D

Reputation: 209358

The Task class adds a bunch of functionality to a FutureTask, but all of the non-obvious parts are to do with providing observable properties and ensuring they are updated on the FX Application Thread. It sounds like you don't need any of the difficult parts: you are querying the task to check its progress (so you don't need observability, i.e. callbacks to be invoked when the progress changes) and you don't have an FX Application Thread on which to schedule updates.

So, for example, if you want to track progress, just add the appropriate property to your Callable implementation. If you want the progress to be accessible from multiple threads, use an atomic reference to represent the progress internally (or at least make it volatile):

import java.util.concurrent.Callable ;
import java.util.concurrent.atomic.AtomicLong ;

public class MyCountingTask implements Callable<Void> {

    private AtomicLong progressCount = new AtomicLong();
    private final long max = 1000 ;

    @Override
    public Void call() throws InterruptedException {

        for (int count = 0; count < max ; count++) {

            progressCount.set(count);

            // in real life, do actual work instead of sleeping...
            Thread.sleep(100);
        }

        progressCount.set(max);

        return null ;
    }

    public double getProgress() {
        return 1.0*progressCount.get() / max ;
    }
}

Upvotes: 2

Related Questions