Sorry about the confusing title. Not sure quite how to phrase it, which may be the problem!
I'm looking for a good abstraction to use for a situation involving concurrent threads.
I've been able to get close, but not quite nail it.
Simplified slightly, I've got two kinds of sensor input being collected on an Android phone - orientation-type stuff and WiFi scans.
When enough of both have been collected, I want to trigger an event to occur which uses the data. However, I don't want to stop there - this process should continue N times.
At first I just used while loops on the condition, e.g.
startCollecting();
while (samplesCollected < X){
// wait
while (directionCount < Y || scanCount < Z){};
// then
doSomeStuff();
samplesCollected++;
}
stopCollecting();
However, I've been told by SO that this is a poor performer, and indeed I have been experiencing some lock up of the UI (even though it's on a different thread), so I decided to utilise java.util.concurrent.
The problem is that I can't quite work out which abstraction to use, perhaps due to my inexperience.
Condition(s) on ReentrantLock:
idea of condition seems great - but it's not the case that I want to control a Shared Resource - I want the data collection to continue in the background whilst the first batch is processed - so where do I call lock? If I don't lock, then it throws an IllegalMonitorStateException.
CountdownLatch:
seems ideal - when the collecting threads have data available, they can call countDown(), and when countDown has been called enough times then the action can continue. But countDown is supposed to be a one-off execution, and I need this to repeat several times.
CyclicBarrier:
docs for CountdownLatch suggest a CyclicBarrier should be used instead if you want the behaviour to be repeatable - but the metaphor of the CyclicBarrier seems totally wrong for this situation, and I don't understand how to use it for this.
I've linked a few related questions below - any guidance would be much appreciated.
Efficiency - use of Thread.yield in loop that waits for variable change
How to make a Java thread wait for another thread's output?
is there a 'block until condition becomes true' function in java?