View Javadoc

1   /**
2    * Copyright 2005-2011 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.test;
17  
18  import org.junit.Assert;
19  
20  import java.util.ArrayList;
21  import java.util.List;
22  
23  /**
24   * Some tests will spawn threads which we want to wait for completion on before we move onto the
25   * next test.  The ThreadMonitor is a place where those outstanding thread can be stored
26   * and handled by the test harnesses tearDown method.
27   * 
28   * @author Kuali Rice Team (rice.collab@kuali.org)
29   *
30   */
31  public class ThreadMonitor {
32  
33  	private static List<Thread> threads = new ArrayList<Thread>();
34  	
35  	public static void addThread(Thread thread) {
36  		threads.add(thread);
37  	}
38  	
39  	/**
40  	 * Waits for all outstanding monitored threads to complete.  If the
41  	 * specified timeout is exceeded for any given thread then the test
42  	 * will fail.
43  	 * 
44  	 * @param maxWait maximum number of milliseconds to wait for any particular thread to die
45  	 */
46  	public static void tearDown(long maxWait) {
47  		Thread thread = null;
48  		try {
49  			for (Thread t : threads) {
50  				thread = t;
51  				thread.join(maxWait);	
52  			}
53  		} catch (InterruptedException e) {
54  			Assert.fail("Failed to wait for test thread to complete: " + (thread == null ? null : thread.getName()));
55  		} finally {
56  			threads.clear();
57  		}
58  	}
59  	
60  }