View Javadoc

1   package cz.cuni.amis.tests;
2   
3   import java.util.Collection;
4   import java.util.concurrent.CountDownLatch;
5   import java.util.concurrent.LinkedBlockingQueue;
6   import java.util.concurrent.ThreadPoolExecutor;
7   import java.util.concurrent.TimeUnit;
8   
9   public class ConcurrencyTest extends BaseTest {
10  
11  	protected void runConcurrent(Collection<ConcurrentTask> tasks, int threads) {
12  		
13  		CountDownLatch latch = new CountDownLatch(tasks.size());
14  		
15  		for (ConcurrentTask task : tasks) {
16  			task.setLatch(latch);
17  			task.setLogger(log);
18  		}
19  
20  		ThreadPoolExecutor executor = new ThreadPoolExecutor(threads, threads, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
21  		
22  		long time = System.currentTimeMillis();
23  		
24  		try {
25  			for (ConcurrentTask task : tasks) {
26  				executor.execute(task);
27  			}
28  			
29  			try {
30  				latch.await();
31  			} catch (InterruptedException e) {
32  				throw new RuntimeException("Interrupted.", e);
33  			}
34  									
35  		} finally {
36  			executor.shutdownNow();
37  		}
38  		
39  		log.info("All tasks finished, time: " + (System.currentTimeMillis() - time) + " ms");
40  		
41  		log.info("Checking thread exceptions...");
42  		
43  		for (ConcurrentTask task : tasks) {
44  			if (task.getException() != null) {
45  				if (task.getException() instanceof RuntimeException) {
46  					throw (RuntimeException)task.getException();
47  				} else {
48  					throw new RuntimeException("At least one task has finished with an exception.", task.getException());
49  				}
50  			}
51  		}
52  		
53  		log.info("All tasks executed OK");
54  		
55  	}
56  	
57  }