Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple times from a method?

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?

like image 620
Lisa Anne Avatar asked Mar 29 '13 16:03

Lisa Anne


1 Answers

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.

like image 134
Nathan Hughes Avatar answered Oct 06 '22 12:10

Nathan Hughes