Sleep and check until condition is true

后端 未结 7 2134
借酒劲吻你
借酒劲吻你 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条回答
  •  旧时难觅i
    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;
            }
        }
    }
    

提交回复
热议问题