Synchronizers are objects that eanble threads to wait for one another, allowing them to coordinate their activities. The most commonly used synchronizers are CountDownLatch and Semaphore.
Countdown latches are single-use barriers that allow one or more threads to wait for one or more other threads to do something. The sole constructor for CountDownLatch takes an int that is the number of times the countDown method must be invoked on the latch before all waiting threads are allowed to proceed.
Lets examine following delicious code, see numbered execution steps.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static long time(Executor executor, int concurrency, | |
final Runnable action) throws InterruptedException { | |
final CountDownLatch ready = new CountDownLatch(concurrency); | |
final CountDownLatch start = new CountDownLatch(1); | |
final CountDownLatch done = new CountDownLatch(concurrency); | |
for (int i = 0; i < concurrency; i++) { | |
executor.execute(new Runnable() { | |
public void run() { | |
ready.countDown(); // STEP 2 - Tell timer we're ready | |
try { | |
start.await(); // STEP 3 - Wait till peers are ready | |
action.run(); // STEP 4 | |
} catch (InterruptedException e) { | |
Thread.currentThread().interrupt(); | |
} finally { | |
done.countDown(); // STEP 7 - Tell timer we're done | |
} | |
} | |
}); | |
} | |
ready.await(); // STEP 1 - Wait for all workers to be ready | |
long startNanos = System.nanoTime(); | |
start.countDown(); // STEP 4 - And they're off! | |
done.await(); // STEP 6 - Wait for all workers to finish | |
return System.nanoTime() - startNanos; //STEP 8 | |
} |
For interval timing, always use System.nanoTime in preference to System.currentTimeMillis. System.nanoTime is both more accurate and more precise, and it is not affected by adjustments to the system's real-time clock.
No comments:
Post a Comment