File: ThreadWaiter.java

package info (click to toggle)
bbmap 38.90%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 21,520 kB
  • sloc: java: 265,882; sh: 14,954; python: 5,247; ansic: 2,074; perl: 96; xml: 38; makefile: 37
file content (73 lines) | stat: -rwxr-xr-x 1,849 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package template;

public class ThreadWaiter {
	
	/** Wait for completion of all threads */
	public static final <T extends Thread> boolean waitForThreads(Iterable<T> iter){

		//Wait for completion of all threads
		boolean success=true;
		for(T t : iter){

			//Wait until this thread has terminated
			while(t.getState()!=Thread.State.TERMINATED){
				try {
					//Attempt a join operation
					t.join();
				} catch (InterruptedException e) {
					//Potentially handle this, if it is expected to occur
					e.printStackTrace();
				}
			}
		}
		
		return success;
	}
	
	public static final <T extends Thread> void startThreads(Iterable<T> iter){
		for(Thread t : iter){t.start();}
	}
	
	/**
	 * @param iter List of Threads.
	 * @return success
	 */
	public static final <T extends Thread> boolean startAndWait(Iterable<T> iter){
		startThreads(iter);
		return waitForThreads(iter);
	}
	
	/**
	 * @param iter List of Threads.
	 * @return success
	 */
	public static final <T extends Thread> boolean startAndWait(Iterable<T> iter, Accumulator<T> acc){
		startThreads(iter);
//		assert(false);
		return waitForThreads(iter, acc);
	}
	
	/** Wait for completion of all threads, and accumulate results */
	public static final <T extends Thread> boolean waitForThreads(Iterable<T> iter, Accumulator<T> acc){

		waitForThreads(iter);
		accumulate(iter, acc);
		return acc.success();
		
	}
	
	/** Accumulate results from all threads */
	private static final <T> boolean accumulate(Iterable<T> iter, Accumulator<T> acc){

		//Wait for completion of all threads
		for(T t : iter){
//			assert(t.getState()==Thread.State.TERMINATED);//Not strictly necessary; requires T to be a thread.

			//Accumulate per-thread statistics
			acc.accumulate(t);
		}
		
		return acc.success();
	}
	
}