Java Reference
In-Depth Information
T1
T2
T3
M
Kick-off threads
Check preconditions
Barrier
Barrier
Check postconditions
Figure 7.6 Synchronizing
tests with multithreaded code
Cooperatively wait for
threads to complete
of barrier or handshake procedure (see figure 7.6) is needed to hold client threads back
until the test is ready to proceed and vice versa.
Thankfully, the log client has an obvious place where you can add such a barrier:
the protected pauseTestThread method, which currently puts the client thread to
sleep for five seconds. You could consider using aspect-orientated programming
( AOP ) to add a barrier to this method, but let's avoid pulling in extra test dependen-
cies and use an anonymous class to override it instead:
final CountDownLatch latch = new CountDownLatch(2);
BundleActivator logClientActivator = new Activator() {
@Override protected void pauseTestThread() {
latch.countDown();
if (latch.getCount() == 0) {
LockSupport.park();
}
}
};
The anonymous class replaces the original pauseTestThread method with one that
uses a countdown latch, initialized with the number of expected log calls. Each time
the client makes a log call, it calls pauseTestThread and counts down the latch. When
no more log calls are expected, the client thread suspends itself and waits for the rest
of the test to shut down. The test code only needs to wait for the latch to reach zero
before it stops the client bundle:
logClientActivator.start(context);
if (!latch.await(5, TimeUnit.SECONDS)) {
fail("Still expecting" + latch.getCount() + " calls");
}
logClientActivator.stop(context);
Search WWH ::




Custom Search