1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.util;
20
21 import static org.junit.Assert.assertTrue;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.apache.hadoop.hbase.SmallTests;
26 import org.junit.Test;
27 import org.junit.experimental.categories.Category;
28
29 @Category(SmallTests.class)
30 public class TestThreads {
31 private static final Log LOG = LogFactory.getLog(TestThreads.class);
32
33 private static final int SLEEP_TIME_MS = 5000;
34 private static final int TOLERANCE_MS = (int) (0.05 * SLEEP_TIME_MS);
35
36 private volatile boolean wasInterrupted;
37
38 @Test(timeout=6000)
39 public void testSleepWithoutInterrupt() throws InterruptedException {
40 Thread sleeper = new Thread(new Runnable() {
41 @Override
42 public void run() {
43 LOG.debug("Sleeper thread: sleeping for " + SLEEP_TIME_MS);
44 Threads.sleepWithoutInterrupt(SLEEP_TIME_MS);
45 LOG.debug("Sleeper thread: finished sleeping");
46 wasInterrupted = Thread.currentThread().isInterrupted();
47 }
48 });
49 LOG.debug("Starting sleeper thread (" + SLEEP_TIME_MS + " ms)");
50 sleeper.start();
51 long startTime = System.currentTimeMillis();
52 LOG.debug("Main thread: sleeping for 500 ms");
53 Threads.sleep(500);
54
55 LOG.debug("Interrupting the sleeper thread and sleeping for 2000 ms");
56 sleeper.interrupt();
57 Threads.sleep(2000);
58
59 LOG.debug("Interrupting the sleeper thread and sleeping for 1000 ms");
60 sleeper.interrupt();
61 Threads.sleep(1000);
62
63 LOG.debug("Interrupting the sleeper thread again");
64 sleeper.interrupt();
65 sleeper.join();
66
67 assertTrue("sleepWithoutInterrupt did not preserve the thread's " +
68 "interrupted status", wasInterrupted);
69
70 long timeElapsed = System.currentTimeMillis() - startTime;
71 assertTrue("Elapsed time " + timeElapsed + " ms is out of the expected " +
72 "range of the sleep time " + SLEEP_TIME_MS,
73 Math.abs(timeElapsed - SLEEP_TIME_MS) < TOLERANCE_MS);
74 LOG.debug("Target sleep time: " + SLEEP_TIME_MS + ", time elapsed: " +
75 timeElapsed);
76 }
77
78
79 @org.junit.Rule
80 public org.apache.hadoop.hbase.ResourceCheckerJUnitRule cu =
81 new org.apache.hadoop.hbase.ResourceCheckerJUnitRule();
82 }
83