Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for the method's return value

Tags:

java

I am really a noob in java, so here's my problem. I have a returned String:

public static String pushToServer(String data){
    //some code here
            Thread.sleep(10000);
            getResponse(); //accesing a public void method
    return string;
    }

The problem is, that return string code return null, because getResponse() method requests a couple of second to get the response. Any way to wait for getResponse() to finish and only then return String?

like image 561
artouiros Avatar asked Dec 28 '12 12:12

artouiros


1 Answers

You can try to use Future objects and Callable tasks. They are quite useful when you want to run some task in another thread and use returned data later. When you want to retrieve the operation results and the task has not finished your operation will simply block and wait until everything is ready to proceed. Here you can find how to use them: http://www.javacodegeeks.com/2011/09/java-concurrency-tutorial-callable.html

Simple example:

public class YourTask implements Callable {
    public String call() throws Exception {
        /* Do what you want to do */
    }
}

Somewhere in code:

Future future = yourThreadPool.submit(new YourTask());

Use the result:

String returnString = future.get(15, TimeUnit.SECONDS);
like image 130
Adam Sznajder Avatar answered Oct 08 '22 00:10

Adam Sznajder