Sleep and check until condition is true

后端 未结 7 2091
借酒劲吻你
借酒劲吻你 2020-12-16 11:39

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 t

相关标签:
7条回答
  • 2020-12-16 11:48

    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.

    0 讨论(0)
  • 2020-12-16 11:51

    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.

    0 讨论(0)
  • 2020-12-16 11:51

    I solved this issue by applying this universal method utilizing functional interface:

    private void waitUntilConditionIsMet(BooleanSupplier awaitedCondition, int timeoutInSec) {
        boolean done;
        long startTime = System.currentTimeMillis();
        do {
            done = awaitedCondition.getAsBoolean();
        } while (!done && System.currentTimeMillis() - startTime < timeoutInSec * 1000);
    }
    

    Then you can implement:

    class StateHolderTest{
        @Test
        public void shouldTurnActive(){
            StateHolder holder = new StateHolder();
            waitUntilConditionIsMet(() -> holder.isActive(), 10);
            assertTrue(holder.isActive);
        }
    }
    
    0 讨论(0)
  • 2020-12-16 12:01

    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.

    0 讨论(0)
  • 2020-12-16 12:05

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-16 12:10

    Awaitility offers a simple and clean solution:

    await().atMost(10, SECONDS).until(() -> condition());
    
    0 讨论(0)
提交回复
热议问题