0

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?

Rodia
  • 1,407
  • 8
  • 22
  • 29
Heijne
  • 113
  • 1
  • 2
  • 6
  • Several solutions are available in this thread: http://stackoverflow.com/questions/289434/how-to-make-a-java-thread-wait-for-another-threads-output?rq=1 – Ivan Pronin Apr 10 '17 at 19:04
  • 2
    If the thread that sends the message needs to wait for the response, why do you wait for the response on another thread? Do it in the same thread, as you have to wait anyway. A thread is useless if it's only used for sleeping. Anyway, what exception does it throw? – RealSkeptic Apr 10 '17 at 19:04
  • It is more or less the same as in [How to make a POST REST call asynchronously in Java](http://stackoverflow.com/questions/43268903/how-to-make-a-post-rest-call-asynchronously-in-java). Replace the HTTP part with your remote call. – andih Apr 10 '17 at 19:07
  • @RealSkeptic. The thread tp listen to the information from the server has to run in any case, because some other messages are coming in as well. It is the call of the fact that I have to use thisThread.interrupt that bothers me. – Heijne Apr 10 '17 at 19:07
  • If the server is sending other stuff over the same connection, how are you going to identify which is the response to the request? – user207421 Apr 11 '17 at 01:57
  • Submit your task to ExecutorServie and wait for Future.get(). You can have a look at example at http://tutorials.jenkov.com/java-util-concurrent/executorservice.html – Ravindra babu Apr 11 '17 at 16:10

1 Answers1

3

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);
hoaz
  • 9,883
  • 4
  • 42
  • 53