Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a value from Runnable

Tags:

java

runnable

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?

like image 782
Grzzzzzzzzzzzzz Avatar asked Dec 03 '12 13:12

Grzzzzzzzzzzzzz


People also ask

How does run () method in runnable work?

run. When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread. The general contract of the method run is that it may take any action whatsoever.

How do you cancel a runnable?

You can call cancel() on the returned Future to stop your Runnable task.

How do you return a thread in Java?

Solution : Create a Handler in UI Thread,which is called as responseHandler. Initialize this Handler from Looper of UI Thread. In HandlerThread , post message on this responseHandler.

What is the difference between runnable and callable in Java?

Callable interface and Runnable interface are used to encapsulate tasks supposed to be executed by another thread. However, Runnable instances can be run by Thread class as well as ExecutorService but Callable instances can only be executed via ExecutorService.


4 Answers

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.

like image 109
Narendra Pathai Avatar answered Sep 24 '22 12:09

Narendra Pathai


public void check() {     ExecutorService executor = Executors.newSingleThreadExecutor();     Future<Integer> result = executor.submit(new Callable<Integer>() {         public Integer call() throws Exception {             return 10;         }     });      try {         int returnValue = result.get();     } catch (Exception exception) {        //handle exception     } } 
like image 20
vishal_aim Avatar answered Sep 24 '22 12:09

vishal_aim


Have a look at the Callable class. This is usually submited via an executor service

It can return a future object which is returned when the thread completes

like image 36
RNJ Avatar answered Sep 24 '22 12:09

RNJ


Yes, there are workaround. Just use queue and put into it value which you want to return. And take this value from another thread.

public class RunnableClass implements Runnable{

        private final BlockingQueue<jaxbResponse> queue;


        public RunnableClass(BlockingQueue<jaxbResponse> queue) {
            this.queue = queue;
        }

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


    public class Endpoint{
        public method_(){
            BlockingQueue<jaxbResponse> queue = new LinkedBlockingQueue<>();

            RunnableClass runcls = new RunnableClass(queue);
            runcls.run()

            jaxbResponse response = queue.take(); // waits until takes value from queue
        }
    }
like image 32
Eldar Agalarov Avatar answered Sep 25 '22 12:09

Eldar Agalarov