0

I am trying to return a String from a FX Task.

Expected output: true,testABC.

Real output: true,null.

The call to the task:

    public static void main(String[] args) {
    ExecutorService pool = Executors.newCachedThreadPool();
    Future<String> my_String = (Future<String>) pool.submit(new my_task());

    try {
        Thread.sleep(500);
        System.out.println(my_String.isDone());
        System.out.println(my_String.get());//gettings the String from the future
    } catch (InterruptedException | ExecutionException ex) {
        Logger.getLogger(Return_test.class.getName()).log(Level.SEVERE, null, ex);
    }}

The task:

public class my_task extends Task<String>{

@Override
protected String call() throws Exception {
    String tempString = "testABC";
    return tempString;
}}
H3AP
  • 1,058
  • 1
  • 10
  • 16

2 Answers2

4

Task implements Runnable, but not Callable. So when you call pool.submit(myTask), you are calling the overloaded form of ExecutorService.submit(...) taking a Runnable. In general, of course, Runnables do not return values, so the Future that is returned from that version of submit(...), as Aerus has already pointed out, just returns null from its get() method (it cannot get a value from the Runnable).

However, Task also extends FutureTask directly, so you can use your task directly to get the result. Just do

Task<String> myTask = new my_task(); // Please use standard naming conventions, i.e. new MyTask();
pool.submit(myTask);

try {
    // sleep is unnecessary, get() will block until ready anyway
    System.out.println(myTask.get());
} catch (InterruptedException | ExecutionException ex) {
    Logger.getLogger(Return_test.class.getName()).log(Level.SEVERE, null, ex);
}
James_D
  • 201,275
  • 16
  • 291
  • 322
  • Thanks this works very nice. I knew it would be possible to retrieve the value because of the FutureTask. Yet i still do not understand why i had to call get() on the task and not on the future? – H3AP May 01 '15 at 12:17
  • 1
    Updated with explanation. – James_D May 01 '15 at 12:24
1

From the submit Javadoc:

The Future's get method will return null upon successful completion.

(Emphasis mine)

Aerus
  • 4,332
  • 5
  • 43
  • 62
  • According to http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html : get() Waits if necessary for the computation to complete, and then retrieves its result. – H3AP May 01 '15 at 11:25
  • Yes, the result being `null` as per the Javadoc snippet above. – Aerus May 01 '15 at 11:39
  • Note which overloaded version of `submit(...)` you are calling: a `Task` is a `Runnable`, but not a `Callable`, so the `submit(...)` method just treats your task as a `Runnable` and calls its `run()` method. It can't get a result from that, since `run()` is `void`. – James_D May 01 '15 at 12:26