I use a CountDownLatch for waiting for a certain event from another component (running in a different thread). The following approach would fit the semantics of my software, but I'm not sure whether it works as a I expect:
mCountDownLatch.await(3000, TimeUnit.MILLISECONDS)
otherComponent.aStaticVolatileVariable = true;
mCountDownLatch.await(3500, TimeUnit.MILLISECONDS);
... <proceed with other stuff>
The scenario should be the following: I wait for 3 seconds, and if the latch is not counted down to 0, I notify the other component with that variable, and then I wait at most 3.5 seconds. If there is timeout again, then I don't care and will proceed with other operations.
Note: I know it doesn't look like that, but the above scenario is totally reasonable and valid in my software.
I did read the documentation of await(int,TimeUnit) and CountDownLatch, but I'm not a Java/Android expert, so I need confirmation. To me, all scenarios look valid:
- If the first await is successful, then the other await will return immediately
- If the first await times out, then the other await is still valid; therefore, if the other thread notices the static signal,the second await might return successfully
- Both await calls time out (this is fine according to my software's semantics)
Am I using await(...) correctly? Can a second await(...) be used in the above way even if a previous await(...) on the same object timed out?
If I understand your question correctly, this test proves that all your assumptions/requirements are true/met. (Run with JUnit and Hamcrest.) Note your code in the
runCodeUnderTest()
method, though it's interspersed with time recording and the timeouts are reduced by a factor of 10.