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