-1

Using a Future like this:

public class Foo implements Future<Object>{
  boolean done=false;
  public boolean isDone(){
    return done;
  }
  public Object get(){
    done = true;
    return "hi";
  }
}

is get() called twice anyhow?

Grim
  • 1,938
  • 10
  • 56
  • 123
  • 1
    I don't understand. Where is `get` called in your example? Why would it be called twice? – Sotirios Delimanolis Dec 03 '14 at 14:43
  • Please show some more code. – javaHunter Dec 03 '14 at 14:44
  • 1
    Normally Futures represent asynchronous tasks that are returned with a implementation by an executor. The typical usage is to submit a task, get a Future, and if you do future.get() the implementation will block until the computation is done. I'm not sure in what context are you using it. more about the normal usage here: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html – AdrianS Dec 03 '14 at 14:48
  • @Blitzkr1eg sure, assuming the `get()` already called, will it be called twice or is the result cached by the `ExecutionService`? – Grim Dec 03 '14 at 15:03
  • The executor doesn't call `get`. – Sotirios Delimanolis Dec 03 '14 at 15:25
  • @SotiriosDelimanolis But does he cache the result and respect if the work is done? OldCurmudgeon had the right answer. – Grim Dec 03 '14 at 15:37
  • Your `ExecutorService` returns a `Future` (an interface). Underneath it all though it has a reference to the implementation, which presumably has a `set` method. When the `ExecutorService` is done processing your `Callable` (or `Runnable`), it will take the returned value (or the exception thrown) and `set` it on the `Future` (and notify any waiters). That result can forever be retrieved through `Future#get`. – Sotirios Delimanolis Dec 03 '14 at 15:39

1 Answers1

2

It is quite possible (and in a multithreaded environment quite common) for get to be called many times by many threads.

If you wish to implement Future<V> you must implement the complete contract - including:

Future... The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready.

You must therefore ensure that a call to get blocks until the task is complete and then deliver the result of the task.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • Too bad, i had hope to let the `ExecutorService` sync to the instance of the class and let him cache the result by itself. – Grim Dec 03 '14 at 15:06