I’ve got a inner class in my class doing some asynchronous processing and setting value on parent class. Ex :
class Myclass{
String test;
public getTestValueFromMyClass(){
//this starts asynchronous processing on my inner class
}
//inner class
class InnerClass extends TimerTask{
//doing something asynchronously, when this process is done
test = "somevalue";
}
}
Now here is the problem from Runner class :
class Runner{
public static void main(String[] args){
Myclass instance = new Myclass();
//This is always null because runner class doesn't wait for Inner class to
//complete asynchronous processing and to set test value
System.out.println(instance.getTestValueFromMyClass());
}
}
How do I get around this?
Others have suggested similar ideas but I’d use a single thread pool with a
Callable.Your class that is doing the asynchronous processing should implement
Callablewhich will return the computed value. In this example it returns aStringbut it could also return your own object with more information.Your
Runnerclass would then create a thread pool, fire off the asynchronous task in the background, and then later wait for it to finish. When you submit aCallablejob to the thread-pool, you get aFutureclass back which can be used to wait for the asynchronous job to finish and to get its return value.