*
* @throws Exception
*/
public void testLatchOnMultiThread() throws Exception
{
final ReusableLatch latch = new ReusableLatch();
latch.countUp(); // We hold at least one, so ThreadWaits won't go away
final int numberOfThreads = 100;
final int numberOfAdds = 100;
class ThreadWait extends Thread
{
private volatile boolean waiting = true;
@Override
public void run()
{
try
{
if (!latch.await(5000))
{
ReusableLatchTest.log.error("Latch timed out");
}
}
catch (Exception e)
{
ReusableLatchTest.log.error(e);
}
waiting = false;
}
}
class ThreadAdd extends Thread
{
private final CountDownLatch latchReady;
private final CountDownLatch latchStart;
ThreadAdd(final CountDownLatch latchReady, final CountDownLatch latchStart)
{
this.latchReady = latchReady;
this.latchStart = latchStart;
}
@Override
public void run()
{
try
{
latchReady.countDown();
// Everybody should start at the same time, to worse concurrency
// effects
latchStart.await();
for (int i = 0; i < numberOfAdds; i++)
{
latch.countUp();
}
}
catch (Exception e)
{
ReusableLatchTest.log.error(e.getMessage(), e);
}
}
}
CountDownLatch latchReady = new CountDownLatch(numberOfThreads);
CountDownLatch latchStart = new CountDownLatch(1);
ThreadAdd[] threadAdds = new ThreadAdd[numberOfThreads];
ThreadWait waits[] = new ThreadWait[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
{
threadAdds[i] = new ThreadAdd(latchReady, latchStart);
threadAdds[i].start();
waits[i] = new ThreadWait();
waits[i].start();
}
latchReady.await();
latchStart.countDown();
for (int i = 0; i < numberOfThreads; i++)
{
threadAdds[i].join();
}
for (int i = 0; i < numberOfThreads; i++)
{
Assert.assertTrue(waits[i].waiting);
}
Assert.assertEquals(numberOfThreads * numberOfAdds + 1, latch.getCount());
class ThreadDown extends Thread
{
private final CountDownLatch latchReady;
private final CountDownLatch latchStart;
ThreadDown(final CountDownLatch latchReady, final CountDownLatch latchStart)
{
this.latchReady = latchReady;
this.latchStart = latchStart;
}
@Override
public void run()
{
try
{
latchReady.countDown();
// Everybody should start at the same time, to worse concurrency
// effects
latchStart.await();
for (int i = 0; i < numberOfAdds; i++)
{
latch.countDown();
}
}
catch (Exception e)
{
ReusableLatchTest.log.error(e.getMessage(), e);
}
}
}
latchReady = new CountDownLatch(numberOfThreads);
latchStart = new CountDownLatch(1);
ThreadDown down[] = new ThreadDown[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
{
down[i] = new ThreadDown(latchReady, latchStart);
down[i].start();
}
latchReady.await();
latchStart.countDown();
for (int i = 0; i < numberOfThreads; i++)
{
down[i].join();
}
Assert.assertEquals(1, latch.getCount());
for (int i = 0; i < numberOfThreads; i++)
{
Assert.assertTrue(waits[i].waiting);
}
latch.countDown();
for (int i = 0; i < numberOfThreads; i++)
{
waits[i].join();
}
Assert.assertEquals(0, latch.getCount());
for (int i = 0; i < numberOfThreads; i++)
{
Assert.assertFalse(waits[i].waiting);
}