I have a method that takes a while to complete. I would like my method to return a "preliminary" result before returning the "final" result.
I would like to understand if it is possible to something like this:
public Object myMethod () {
/*some computation here*/
return firstResult;
/*
very long computation here
*/
return finalResult;
}
Is this even possible or can you suggest some kind of workaround?
You could put the long-running task on an executor (which would execute the task asynchronously using a thread pool) and return a Future that you can use later to get the answer. When you call get
on the future, it blocks until the task finishes, so you can use your initial answer right away and call Future.get
when you need more precision later, having given the task some time to finish.
The return value might look like this:
class MyMethodReturnStuff {
private Object quickAnswer;
private Future longAnswer;
private long startTime = System.currentTimeMillis();
MyMethodReturnStuff(Object quickAnswer, Future longAnswer) {
this.quickAnswer = quickAnswer;
this.longAnswer = longAnswer;
}
Object getAnswer(long expectedDelay) {
return System.currentTimeMillis() - startTime < expectedDelay ?
quickAnswer : longAnswer.get();
}
}
If you expect the long calculation to take 5 seconds, calling getAnswer(5000)
would return the quick answer if less than 5 seconds has passed and would return the longAnswer otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With