Sleep and check until condition is true

2019-02-08 00:22发布

问题:

Is there a library in Java that does the following? A thread should repeatedly sleep for x milliseconds until a condition becomes true or the max time is reached.

This situation mostly occurs when a test waits for some condition to become true. The condition is influenced by another thread.

[EDIT]Just to make it clearer, I want the test to wait for only X ms before it fails. It cannot wait forever for a condition to become true. I am adding a contrived example.

class StateHolder{
    boolean active = false;
    StateHolder(){
        new Thread(new Runnable(){
            public void run(){
                active = true;
            }
        }, "State-Changer").start()
    }
    boolean isActive(){
        return active;
    }
}


class StateHolderTest{
    @Test
    public void shouldTurnActive(){
        StateHolder holder = new StateHolder();
        assertTrue(holder.isActive); // i want this call not to fail 
    }
}

回答1:

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.



回答2:

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)



回答3:

Awaitility offers a simple and clean solution:

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



回答4:

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;
        }
    }
}


回答5:

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.



回答6:

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.