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 java.util.concurrent.atomic.AtomicBoolean;
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27 import org.apache.hadoop.hbase.testclassification.MiscTests;
28 import org.apache.hadoop.hbase.testclassification.SmallTests;
29 import org.junit.Test;
30 import org.junit.experimental.categories.Category;
31
32 @Category({MiscTests.class, SmallTests.class})
33 public class TestThreads {
34 private static final Log LOG = LogFactory.getLog(TestThreads.class);
35
36 private static final int SLEEP_TIME_MS = 3000;
37 private static final int TOLERANCE_MS = (int) (0.10 * SLEEP_TIME_MS);
38
39 private final AtomicBoolean wasInterrupted = new AtomicBoolean(false);
40
41 @Test(timeout=60000)
42 public void testSleepWithoutInterrupt() throws InterruptedException {
43 Thread sleeper = new Thread(new Runnable() {
44 @Override
45 public void run() {
46 LOG.debug("Sleeper thread: sleeping for " + SLEEP_TIME_MS);
47 Threads.sleepWithoutInterrupt(SLEEP_TIME_MS);
48 LOG.debug("Sleeper thread: finished sleeping");
49 wasInterrupted.set(Thread.currentThread().isInterrupted());
50 }
51 });
52 LOG.debug("Starting sleeper thread (" + SLEEP_TIME_MS + " ms)");
53 sleeper.start();
54 long startTime = System.currentTimeMillis();
55 LOG.debug("Main thread: sleeping for 200 ms");
56 Threads.sleep(200);
57
58 LOG.debug("Interrupting the sleeper thread and sleeping for 500 ms");
59 sleeper.interrupt();
60 Threads.sleep(500);
61
62 LOG.debug("Interrupting the sleeper thread and sleeping for 800 ms");
63 sleeper.interrupt();
64 Threads.sleep(800);
65
66 LOG.debug("Interrupting the sleeper thread again");
67 sleeper.interrupt();
68 sleeper.join();
69
70 assertTrue("sleepWithoutInterrupt did not preserve the thread's " +
71 "interrupted status", wasInterrupted.get());
72
73 long timeElapsed = System.currentTimeMillis() - startTime;
74
75 assertTrue("Elapsed time " + timeElapsed + " ms is out of the expected " +
76 " sleep time of " + SLEEP_TIME_MS, SLEEP_TIME_MS - timeElapsed < TOLERANCE_MS);
77 LOG.debug("Target sleep time: " + SLEEP_TIME_MS + ", time elapsed: " +
78 timeElapsed);
79 }
80 }