Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get to FutureTask execution state?

I have a singleThreadExecutor in order to execute the tasks I submit to it in serial order i.e. one task after another, no parallel execution.

I have runnable which goes something like this

MyRunnable implements Runnable {

@Override
public void run() {
    try {
        Thread.sleep(30000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

}

When I submit ,for example, three instances of MyRunnable to the afore-mentioned single thread executor, I would expect to have the first task executing and because of the Thread.sleep has Its executing thread in TIMED_WAITING (I may be wrong about the specific state). The other two tasks should not have threads assigned to execute them, at least not until the first task has finished.

So my question is how to get this state via the FutureTask API or somehow get to the thread that is executing the task (if there is no such thread then the task is waiting to be executed or pending) and get Its state or perhaps by some other means?

FutureTask only defines isCanceled() and isDone() methods, but those are not quite enough to describe all the possible execution statuses of the Task.

like image 784
Svilen Avatar asked Aug 03 '11 20:08

Svilen


1 Answers

You could wrap anything you submit to this service in a Runnable that records when its run method is entered.

public class RecordingRunnable implements Runnable {
    private final Runnable actualTask;
    private volatile boolean isRunning = false;
    //constructor, etc

    public void run() {
        isRunning = true;
        actualTask.run();
        isRunning = false;
    }

    public boolean isRunning() {
       return isRunning;
    }
}
like image 99
Mark Peters Avatar answered Sep 19 '22 11:09

Mark Peters