Sleep and check until condition is true

删除回忆录丶 提交于 2019-11-30 11:15:19

EDIT

Most answers focus on the low level API with waits and notifies or Conditions (which work more or less the same way): it is difficult to get right when you are not used to it. Proof: 2 of these answers don't use wait correctly.
java.util.concurrent offers you a high level API where all those intricacies have been hidden.

IMHO, there is no point using a wait/notify pattern when there is a built-in class in the concurrent package that achieves the same.


A CountDownLatch with an initial count of 1 does exactly that:

  • When the condition becomes true, call latch.countdown();
  • in your waiting thread, use : boolean ok = latch.await(1, TimeUnit.SECONDS);

Contrived example:

final CountDownLatch done = new CountDownLatch(1);

new Thread(new Runnable() {

    @Override
    public void run() {
        longProcessing();
        done.countDown();
    }
}).start();

//in your waiting thread:
boolean processingCompleteWithin1Second = done.await(1, TimeUnit.SECONDS);

Note: CountDownLatches are thread safe.

thisismydesign

Awaitility offers a simple and clean solution:

await().atMost(10, SECONDS).until(() -> condition());

You should be using a Condition.

If you would like to have a timeout in addition to the condition, see await(long time, TimeUnit unit)

I was looking for a solution like what Awaitility provides. I think I chose an incorrect example in my question. What I meant was in a situation where you are expecting an asynchronous event to happen which is created by a third party service and the client cannot modify the service to offer notifications. A more reasonable example would be the one below.

class ThirdPartyService {

    ThirdPartyService() {
        new Thread() {

            public void run() {
                ServerSocket serverSocket = new ServerSocket(300);
                Socket socket = serverSocket.accept();
                // ... handle socket ...
            }
        }.start();
    }
}

class ThirdPartyTest {

    @Before
    public void startThirdPartyService() {
        new ThirdPartyService();
    }

    @Test
    public void assertThirdPartyServiceBecomesAvailableForService() {
        Client client = new Client();
        Awaitility.await().atMost(50, SECONDS).untilCall(to(client).canConnectTo(300), equalTo(true));
    }
}

class Client {

    public boolean canConnect(int port) {
        try {
            Socket socket = new Socket(port);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
jco.owens

You should not sleep and check and sleep and check. You want to wait on a condition variable and have the condition change and wake up the thread when its time to do something.

Jonathan

It seems like what you want to do is check the condition and then if it is false wait until timeout. Then, in the other thread, notifyAll once the operation is complete.

Waiter

synchronized(sharedObject){
  if(conditionIsFalse){
       sharedObject.wait(timeout);
       if(conditionIsFalse){ //check if this was woken up by a notify or something else
           //report some error
       }
       else{
           //do stuff when true
       }
  }
  else{
      //do stuff when true
  }
}

Changer

  synchronized(sharedObject){
   //do stuff to change the condition
   sharedObject.notifyAll();
 }

That should do the trick for you. You can also do it using a spin lock, but you would need to check the timeout every time you go through the loop. The code might actually be a bit simpler though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!