tempus-fugit

Java micro-library for writing & testing concurrent code

Conditions

Conditions are part of our everyday language. The Condition interface captures a conditional as something that can be reused. For example, waiting for something can be achieved using the WaitFor (see waiting) class and an anonymous Condition. For example,

1
2
3
4
5
6
7
private void waitForShutdown() throws TimeoutException {
    waitOrTimeout(new Condition() {
        public boolean isSatisfied() {
            return server.isShutdown();
        }
    }, timeout);
 }

will wait for some server to indicate that it has shutdown. The Conditions class collects useful Condition objects such as not. There is also a useful Condition to indicate if a thread is in a waiting state in ThreadUtils.

Some common thread related conditions have been collected in the Conditions class. These include a not condition to invert the result of some other condition and various thread state related conditions such as checking if a a thread alive. See the miscellaneous thread utils section for details.

For testing purposes, you might want to assert against the outcome of a Condition. The Conditions class has an assertThat method which takes a Matcher<Boolean> for use with JUnit. For example, you could assert against a condition using vanilla JUnit like this.

1
Assert.assertThat(not(TRUE).isSatisfied(), is(false));

or using the Conditions class, you can tidy the assert up to look like this.

1
Conditions.assertThat(not(TRUE), is(false));

If you have Matchers available in your production code, you can use this with flexible waits, for example,

1
WaitFor.waitOrTimeout(Conditions.assertion("hello", is(not(equalTo("goodbye")))), timeout(millis(100)));

Next, Testing Time Sensitive Code: Waiting For Conditions »