tambalolo
tambalolo

Reputation: 1075

Waiting callback without pausing calling thread. Am I doing this right?

    public class Threadz implements Callable<String>{
    private boolean flag = false;
    
    @Override
    public String call() throws Exception {
        // TODO Auto-generated method stub
        for(int i = 0; i < 3; i++){
            Thread.sleep(2000);
        }
        flag = true;
        return "Done";
    }
    
    public boolean isDone(){
        return flag;
    }
}

    public class MyMain {
    public static void main(String[] args) {
        ExecutorService exe = Executors.newSingleThreadExecutor();
        Threadz threadz = new Threadz();
        Callable<String> cthread = threadz;
        Future<String> fut = exe.submit(cthread);
        
        while(true){
            try {
                if(!threadz.isDone())
                    System.out.println("Do something while waiting...");
                else{
                    System.out.println(fut.get());
                    System.out.print("Do something with the result...");
                    break;
                }
                Thread.sleep(1000);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

My goal with the above code is to spawn a thread that will return a result but the calling thread should not be paused while waiting for the result. This actually works but am I doing this correctly? Is there a proper way of doing this? And also, is the callable thread automatically dies (frees resources and memory) after returning the result?

Upvotes: 0

Views: 953

Answers (1)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

String callbackReturn = threadz.get();

It waits if necessary for the computation to complete, and then retrieves its result.

        ExecutorService exe = Executors.newSingleThreadExecutor();
        Threadz threadz = new Threadz();
        Callable<String> cthread = threadz;
        Future<String> fut = exe.submit(cthread);
        String callbackReturn = threadz.get();

Current thread will wait here. if you dont want to pause it, then handle it result in other thread.

Upvotes: 1

Related Questions