I am using the CountDownLatch to synchronize an initialization process between two threads and I was wondering about the proper handling of the InterruptedException that it might throw.
the code i initially wrote was this:
private CountDownLatch initWaitHandle = new CountDownLatch(1);
/**
* This method will block until the thread has fully initialized, this should only be called from different threads Ensure that the thread has started before this is called.
*/
public void ensureInitialized()
{
assert this.isAlive() : "The thread should be started before calling this method.";
assert Thread.currentThread() != this, "This should be called from a different thread (potential deadlock)";
while(true)
{
try
{
//we wait until the updater thread initializes the cache
//that way we know
initWaitHandle.await();
break;//if we get here the latch is zero and we are done
}
catch (InterruptedException e)
{
LOG.warn("Thread interrupted", e);
}
}
}
Does this pattern make sense? Basically is it a good idea to ignore the InterruptedException just keep waiting until it succeeds. I guess I just don't understand the situations under which this would get interrupted so I don't know if I should be handling them differently.
Why would an InterruptedException get thrown here, what is the best practice for handling it?
CountDownLatch is used to make sure that a task waits for other threads before it starts. To understand its application, let us consider a server where the main task can only start when all the required services have started.
CountDownLatch class is a synchronization aid which allows one or more thread to wait until the mandatory operations are performed by other threads. CountDownLatch is initialized with a given count of threads which are required to be completed before the main thread. CountDownLatch.
Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception.
As stated in the definitions, CyclicBarrier allows a number of threads to wait on each other, whereas CountDownLatch allows one or more threads to wait for a number of tasks to complete. In short, CyclicBarrier maintains a count of threads whereas CountDownLatch maintains a count of tasks.
If you do not foresee any legitimate reason that the Thread
could be interrupted, and can't think of any reasonable reaction to it, I'd say you should do
catch (InterruptedException e){
throw new AssertionError("Unexpected Interruption",e);
}
That way the application will clearly fail if such interruption happens, making it easier to discover during the testing. Then you can think about how the application should handle that, or if they are any problem in the design.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With