Returning a value from Runnable

Grzzzzzzzzzzzzz picture Grzzzzzzzzzzzzz · Dec 3, 2012 · Viewed 85.5k times · Source

The run method of Runnable has return type void and cannot return a value. I wonder however if there is any workaround of this.

I have a method like this:

public class Endpoint {
    public method() {
       Runnable runcls = new RunnableClass();
       runcls.run()
    }
}

The method run is like this:

public class RunnableClass implements Runnable {
    
    public JaxbResponse response;

    public void run() {
        int id = inputProxy.input(chain);
        response = outputProxy.input();
    }
}

I want to have access to response variable in method. Is this possible?

Answer

Narendra Pathai picture Narendra Pathai · Dec 3, 2012

Use Callable<V> instead of using Runnable interface.

Example:

public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<>();

    for (String word : args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }

    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }

    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
}

In this example, you will also need to implement the class WordLengthCallable, which implements the Callable interface.