Have you thought about some classes from java.util.concurrent - for example, BlockingQueue? You can use:
BlockingQueue<Boolean> conditionMet = new BlockingQueue<Boolean>; conditionMet.poll(10,TimeUnit.SECONDS);
And then in the code that changes your condition, do the following:
conditionMet.put(true);
EDIT:
Another example of a java.util.concurrent form might be CountDownLatch:
CountDownLatch siteWasRenderedLatch = new CountDownLatch(1); boolean siteWasRendered = siteWasRenderedLatch.await(10,TimeUnit.SECONDS);
This way you will wait 10 seconds or until the latch reaches zero. To reach zero, you only need:
siteWasRenderedLatch.countDown();
This way you will not need to use the locks that are needed in the example conditions provided by @Adrian. I think it's just simpler and more straightforward.
And if you don't like the names โLatchโ or โQueueโ, you can always transfer them to your own class called ie LimitedTimeCondition:
public class LimitedTimeCondition { private CountDownLatch conditionMetLatch; private Integer unitsCount; private TimeUnit unit; public LimitedTimeCondition(final Integer unitsCount, final TimeUnit unit) { conditionMetLatch = new CountDownLatch(1); this.unitsCount = unitsCount; this.unit = unit; } public boolean waitForConditionToBeMet() { try { return conditionMetLatch.await(unitsCount, unit); } catch (final InterruptedException e) { System.out.println("Someone has disturbed the condition awaiter."); return false; } } public void conditionWasMet() { conditionMetLatch.countDown(); } }
And the use will be:
LimitedTimeCondition siteRenderedCondition = new LimitedTimeCondition(10, TimeUnit.SECONDS); // ... // if (siteRenderedCondition.waitForConditionToBeMet()) { doStuff(); } else { System.out.println("Site was not rendered properly"); } // ... // in condition checker/achiever: if (siteWasRendered) { condition.conditionWasMet(); }
source share