View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.io;
18  
19  import org.apache.commons.io.testtools.TestUtils;
20  import org.junit.Test;
21  
22  import static org.junit.Assert.assertNull;
23  import static org.junit.Assert.fail;
24  
25  /**
26   * Tests for {@link ThreadMonitor}.
27   */
28  public class ThreadMonitorTestCase {
29  
30      /**
31       * Test timeout.
32       */
33      @Test
34      public void testTimeout() {
35          try {
36              final Thread monitor = ThreadMonitor.start(100);
37              TestUtils.sleep(200);
38              ThreadMonitor.stop(monitor);
39              fail("Expected InterruptedException");
40          } catch (final InterruptedException e) {
41              // expected result - timeout
42          }
43      }
44  
45      /**
46       * Test task completed before timeout.
47       */
48      @Test
49      public void testCompletedWithoutTimeout() {
50          try {
51              final Thread monitor = ThreadMonitor.start(200);
52              TestUtils.sleep(100);
53              ThreadMonitor.stop(monitor);
54          } catch (final InterruptedException e) {
55              fail("Timed Out");
56          }
57      }
58  
59      /**
60       * Test No timeout.
61       */
62      @Test
63      public void testNoTimeout() {
64  
65          // timeout = -1
66          try {
67              final Thread monitor = ThreadMonitor.start(-1);
68              assertNull("Timeout -1, Monitor should be null", monitor);
69              TestUtils.sleep(100);
70              ThreadMonitor.stop(monitor);
71          } catch (final Exception e) {
72              fail("Timeout -1, threw " + e);
73          }
74  
75          // timeout = 0
76          try {
77              final Thread monitor = ThreadMonitor.start(0);
78              assertNull("Timeout 0, Monitor should be null", monitor);
79              TestUtils.sleep(100);
80              ThreadMonitor.stop(monitor);
81          } catch (final Exception e) {
82              fail("Timeout 0, threw " + e);
83          }
84      }
85  }
86