| 1 | package com.hammurapi.common.concurrent; |
| 2 | |
| 3 | |
| 4 | /** |
| 5 | * This class increments counter when created and |
| 6 | * decrements when run() method exits. When counter reaches zero, this |
| 7 | * class invokes notifyAll() on the counter. The class shall be used for |
| 8 | * parallel execution of tasks when it is required to wait until all tasks |
| 9 | * complete. |
| 10 | * @author Pavel Vlasov |
| 11 | * |
| 12 | */ |
| 13 | public class CountedRunnable implements Runnable { |
| 14 | |
| 15 | /** |
| 16 | * Counter to use with CounterRunnable. |
| 17 | * @author Pavel Vlasov |
| 18 | */ |
| 19 | public static class Counter { |
| 20 | private int counter; |
| 21 | |
| 22 | synchronized void inc() { |
| 23 | ++counter; |
| 24 | } |
| 25 | |
| 26 | synchronized void dec() { |
| 27 | if (--counter <= 0) { |
| 28 | notifyAll(); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | public synchronized void join() throws InterruptedException { |
| 33 | while (counter>0) { |
| 34 | wait(); |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | private Counter counter; |
| 40 | private Runnable master; |
| 41 | |
| 42 | public CountedRunnable(Counter counter, Runnable master) { |
| 43 | this.counter = counter; |
| 44 | counter.inc(); |
| 45 | this.master = master; |
| 46 | } |
| 47 | |
| 48 | final public void run() { |
| 49 | try { |
| 50 | master.run(); |
| 51 | } finally { |
| 52 | counter.dec(); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | } |