Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java:Get a value from a thread...?

How can return a variable from a thead (I have the threads handle too). Static variables will not work in this case.

Update: Here is one twist, how can I do this without having to block and wait for the result? I need to be able to poll the created thread and kill it if it is hanging for too long (eg> 1 minute), then continue on in the main thread if the spawned thread is taking too long.

like image 281
Zombies Avatar asked Mar 09 '10 23:03

Zombies


2 Answers

Use Callable<V> instead of Thread (or Runnable) so that you can get result as Future<V> and use ExecutorService to invoke it.

Here's an SSCCE, just copy'n'paste'n'run it:

package com.stackoverflow.q2413389;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Test {

    public static void main(String... args) throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool();
        List<Future<String>> results = executor.invokeAll(Arrays.asList(new Task()));
        for (Future<String> result : results) {
            System.out.println(result.get()); // Prints "myResult" after 2 seconds.
        }
        executor.shutdown();
    }

}

class Task implements Callable<String> {

    public String call() throws Exception {
        Thread.sleep(2000); // Do your running task here, this example lasts 2 seconds.
        return "myResult";
    }

}

Update: as per your update with the question how to kill it after a timeout, make use of ScheduledExecutorService instead. Here's the slightly changed code:

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
List<Future<String>> results = executor.invokeAll(Arrays.asList(new Task()), 1, TimeUnit.SECONDS); // Timeout of 1 second.
for (Future<String> result : results) {
    if (!result.isCancelled()) {
        System.out.println(result.get()); // Won't be printed as the "actual" processing took 2 seconds.
    } else {
        System.out.println("Task timed out.");
    }
}
executor.shutdown();
like image 146
BalusC Avatar answered Oct 04 '22 18:10

BalusC


If I understand your question (how to access a thread object's member value) you can use this simple approach:

MyObject a = new MyObject(); new Thread(a).start();

Just remember to implement the Runnable interface for MyObject and to have appropriate Getters.

If you are wanting to return a variable you can create a member in the class And do a while-loop till the thread finishes execution.

like image 37
Vals Avatar answered Oct 04 '22 18:10

Vals