Heijne
Heijne

Reputation: 183

How to make a thread wait for a server response

I am currently writing a small Java program where I have a client sending commands to a server. A separate Thread is dealing with replies from that server (the reply is usually pretty fast). Ideally I pause the Thread that made the server request until such time as the reply is received or until some time limit is exceeded.

My current solution looks like this:

public void waitForResponse(){
    thisThread = Thread.currentThread();
    try {
        thisThread.sleep(10000);
        //This should not happen.
        System.exit(1);
    }
    catch (InterruptedException e){
        //continue with the main programm
    }
}

public void notifyOKCommandReceived() {
    if(thisThread != null){
        thisThread.interrupt();
    }
}

The main problem is: This code does throw an exception when everything is going as it should and terminates when something bad happens. What is a good way to fix this?

Upvotes: 0

Views: 3153

Answers (1)

hoaz
hoaz

Reputation: 10163

There are multiple concurrency primitives which allow you to implement thread communication. You can use CountDownLatch to accomplish similar result:

public void waitForResponse() {
    boolean result = latch.await(10, TimeUnit.SECONDS);
    // check result and react correspondingly
}

public void notifyOKCommandReceived() {
    latch.countDown();
}

Initialize latch before sending request as follows:

latch = new CountDownLatch(1);

Upvotes: 3

Related Questions