Java 5: java.util.concurrent.FutureTask - semantics of cancel () and done ()

I'm currently looking for a nasty bug in a multi-threaded environment using FutureTasks and Executors. The basic idea is to have a fixed number of threads execute separate FutureTasks that calculate the result that should be displayed in the table (not paying attention to the GUI aspect here).

I've been looking at this for so long, I'm starting to doubt my sanity.

Consider this piece of code:

public class MyTask extends FutureTask<Result> {
   private String cellId;
   ...
   protected void done() {
      if (isCancelled()) return;
      try {
          Result r = get(); // should not wait, because we are done
          ... // some processing with r
          sendMessage(cellId, r);
      } catch (ExecutionException e) { // thrown from get
         ... 
      } catch (InterruptedException e) { // thrown from get
         ... 
      }
   }
   ...
}

When done()Executor is called that processes the MyTask instance, I check to see if I got there because the task was canceled. If so, I skip all other steps, especially I do not name sendMessage().

The documentation for FutureTask.done () says:

, , isDone ( ). . , . , , , . ( API)

, FutureTask, done(). , isCancelled() , - cancel()? isCancelled() == true ?

, , ? isDone(), , , isCancelled() , , .

, , .

+3
4

API ( ):

public boolean cancel (boolean mayInterruptIfRunning)

, : Future

. , , - .

, FutureTask , , isDone.

+3

FutureTask#done() - run() , , cancel() , . . , a FutureTask , , , , " ".

, FutureTask#done() isCancelled() isDone() true, . isDone() . set() setException(Throwable) , AQS, , . , , . - " ", , , .

, , , - get().

+4

"" , <V> , ExecutorService? , , : Callable <V> ExecutorService. , <V> (, ), <V> , . . <V> .get(), , , get, -.

, ExecutorService: . . , .

FutureTask <V> . Callable <V> . - , Callable <V> , Thread.interrupted().

+3

, cancel(), Future done() , .

-1

Source: https://habr.com/ru/post/1714428/


All Articles