Skip to content

Commit 3b3008b

Browse files
authored
Merge pull request eugenp#4623 from chandra1123/BAEL-1757-3
Added unit test for Thread.Join
2 parents 66ede7f + 463d159 commit 3b3008b

1 file changed

Lines changed: 95 additions & 0 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package com.baeldung.thread.join;
2+
3+
import static org.junit.Assert.assertFalse;
4+
import static org.junit.Assert.assertTrue;
5+
6+
import java.util.logging.Logger;
7+
8+
import org.junit.Ignore;
9+
import org.junit.Test;
10+
11+
/**
12+
* Demonstrates Thread.join behavior.
13+
*
14+
*/
15+
public class ThreadJoinUnitTest {
16+
17+
final static Logger LOGGER = Logger.getLogger(ThreadJoinUnitTest.class.getName());
18+
19+
class SampleThread extends Thread {
20+
public int processingCount = 0;
21+
22+
SampleThread(int processingCount) {
23+
this.processingCount = processingCount;
24+
LOGGER.info("Thread " + this.getName() + " created");
25+
}
26+
27+
@Override
28+
public void run() {
29+
LOGGER.info("Thread " + this.getName() + " started");
30+
while (processingCount > 0) {
31+
try {
32+
Thread.sleep(1000); // Simulate some work being done by thread
33+
} catch (InterruptedException e) {
34+
LOGGER.info("Thread " + this.getName() + " interrupted.");
35+
}
36+
processingCount--;
37+
LOGGER.info("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
38+
}
39+
LOGGER.info("Thread " + this.getName() + " exiting");
40+
}
41+
}
42+
43+
@Test
44+
public void givenNewThread_whenJoinCalled_returnsImmediately() throws InterruptedException {
45+
Thread t1 = new SampleThread(0);
46+
LOGGER.info("Invoking join.");
47+
t1.join();
48+
LOGGER.info("Returned from join");
49+
LOGGER.info("Thread state is" + t1.getState());
50+
assertFalse(t1.isAlive());
51+
}
52+
53+
@Test
54+
public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
55+
throws InterruptedException {
56+
Thread t2 = new SampleThread(1);
57+
t2.start();
58+
LOGGER.info("Invoking join.");
59+
t2.join();
60+
LOGGER.info("Returned from join");
61+
assertFalse(t2.isAlive());
62+
}
63+
64+
@Test
65+
public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
66+
throws InterruptedException {
67+
Thread t3 = new SampleThread(10);
68+
t3.start();
69+
t3.join(1000);
70+
assertTrue(t3.isAlive());
71+
}
72+
73+
@Test
74+
@Ignore
75+
public void givenThreadTerminated_checkForEffect_notGuaranteed()
76+
throws InterruptedException {
77+
SampleThread t4 = new SampleThread(10);
78+
t4.start();
79+
//not guaranteed to stop even if t4 finishes.
80+
do {
81+
82+
} while (t4.processingCount > 0);
83+
}
84+
85+
@Test
86+
public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
87+
throws InterruptedException {
88+
SampleThread t4 = new SampleThread(10);
89+
t4.start();
90+
do {
91+
t4.join(100);
92+
} while (t4.processingCount > 0);
93+
}
94+
95+
}

0 commit comments

Comments
 (0)