Skip to content

Commit 90c2739

Browse files
tamasradumaibin
authored andcommitted
Radu/bael 1265 junit updates (eugenp#2965)
* Code for test article: Different Types of Bean Injection in Spring * Adding jUnits for test article: Different Types of Bean Injection in Spring * BAEL-1265: Adding jUnit for article * BAEL-1265: Closing ExecutorService in jUnit * BAEL-1265: Adding jUnit for CountDownLatch and example for ExecutorService.awaitTermination
1 parent 2e7d254 commit 90c2739

8 files changed

Lines changed: 211 additions & 10 deletions

File tree

‎core-java-concurrency/src/main/java/com/baeldung/concurrent/executorservice/DelayedCallable.java‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
package com.baeldung.concurrent.executorservice;
22

33
import java.util.concurrent.Callable;
4+
import java.util.concurrent.CountDownLatch;
45

56
public class DelayedCallable implements Callable<String> {
67

78
private String name;
89
private long period;
10+
private CountDownLatch latch;
11+
12+
public DelayedCallable(String name, long period, CountDownLatch latch) {
13+
this(name, period);
14+
this.latch = latch;
15+
}
916

1017
public DelayedCallable(String name, long period) {
1118
this.name = name;
@@ -16,9 +23,15 @@ public String call() {
1623

1724
try {
1825
Thread.sleep(period);
26+
27+
if (latch != null) {
28+
latch.countDown();
29+
}
30+
1931
} catch (InterruptedException ex) {
2032
// handle exception
2133
ex.printStackTrace();
34+
Thread.currentThread().interrupt();
2235
}
2336

2437
return name;

‎core-java-concurrency/src/test/java/com/baeldung/concurrent/executorservice/WaitingForThreadsToFinishTest.java‎

Lines changed: 78 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,91 @@
99
import java.util.concurrent.*;
1010

1111
import static junit.framework.TestCase.assertTrue;
12+
import static org.junit.Assert.fail;
1213

1314
public class WaitingForThreadsToFinishTest {
1415

1516
private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishTest.class);
1617
private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
1718

19+
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
20+
threadPool.shutdown();
21+
try {
22+
if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
23+
threadPool.shutdownNow();
24+
}
25+
} catch (InterruptedException ex) {
26+
threadPool.shutdownNow();
27+
Thread.currentThread().interrupt();
28+
}
29+
}
30+
31+
@Test
32+
public void givenMultipleThreads_whenUsingCountDownLatch_thenMainShoudWaitForAllToFinish() {
33+
34+
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
35+
36+
try {
37+
long startTime = System.currentTimeMillis();
38+
39+
// create a CountDownLatch that waits for the 2 threads to finish
40+
CountDownLatch latch = new CountDownLatch(2);
41+
42+
for (int i = 0; i < 2; i++) {
43+
WORKER_THREAD_POOL.submit(new Runnable() {
44+
@Override
45+
public void run() {
46+
try {
47+
Thread.sleep(1000);
48+
latch.countDown();
49+
} catch (InterruptedException e) {
50+
e.printStackTrace();
51+
Thread.currentThread().interrupt();
52+
}
53+
}
54+
});
55+
}
56+
57+
// wait for the latch to be decremented by the two threads
58+
latch.await();
59+
60+
long processingTime = System.currentTimeMillis() - startTime;
61+
assertTrue(processingTime >= 1000);
62+
63+
} catch (InterruptedException e) {
64+
e.printStackTrace();
65+
}
66+
67+
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
68+
}
69+
1870
@Test
1971
public void givenMultipleThreads_whenInvokeAll_thenMainThreadShouldWaitForAllToFinish() {
2072

2173
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
2274

23-
List<Callable<String>> callables = Arrays.asList(new DelayedCallable("fast thread", 100), new DelayedCallable("slow thread", 3000));
24-
75+
List<Callable<String>> callables = Arrays.asList(
76+
new DelayedCallable("fast thread", 100),
77+
new DelayedCallable("slow thread", 3000));
78+
2579
try {
2680
long startProcessingTime = System.currentTimeMillis();
2781
List<Future<String>> futures = WORKER_THREAD_POOL.invokeAll(callables);
82+
83+
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
84+
85+
try {
86+
WORKER_THREAD_POOL.submit(new Callable<String>() {
87+
@Override
88+
public String call() throws Exception {
89+
fail("This thread should have been rejected !");
90+
Thread.sleep(1000000);
91+
return null;
92+
}
93+
});
94+
} catch (RejectedExecutionException ex) {
95+
//
96+
}
2897

2998
long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
3099
assertTrue(totalProcessingTime >= 3000);
@@ -39,24 +108,22 @@ public void givenMultipleThreads_whenInvokeAll_thenMainThreadShouldWaitForAllToF
39108

40109
} catch (ExecutionException | InterruptedException ex) {
41110
ex.printStackTrace();
42-
}
43-
44-
WORKER_THREAD_POOL.shutdown();
111+
}
45112
}
46113

47114
@Test
48115
public void givenMultipleThreads_whenUsingCompletionService_thenMainThreadShouldWaitForAllToFinish() {
49116

50117
CompletionService<String> service = new ExecutorCompletionService<>(WORKER_THREAD_POOL);
51118

52-
List<Callable<String>> callables = Arrays.asList(new DelayedCallable("fast thread", 100), new DelayedCallable("slow thread", 3000));
119+
List<Callable<String>> callables = Arrays.asList(
120+
new DelayedCallable("fast thread", 100),
121+
new DelayedCallable("slow thread", 3000));
53122

54123
for (Callable<String> callable : callables) {
55124
service.submit(callable);
56125
}
57126

58-
WORKER_THREAD_POOL.shutdown();
59-
60127
try {
61128

62129
long startProcessingTime = System.currentTimeMillis();
@@ -79,8 +146,9 @@ public void givenMultipleThreads_whenUsingCompletionService_thenMainThreadShould
79146

80147
} catch (ExecutionException | InterruptedException ex) {
81148
ex.printStackTrace();
149+
} finally {
150+
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
82151
}
83-
84152
}
85153

86154
@Test
@@ -142,6 +210,6 @@ public void givenMultipleThreads_whenUsingCompletableFutures_thenMainThreadShoul
142210
e.printStackTrace();
143211
}
144212

145-
WORKER_THREAD_POOL.shutdown();
213+
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
146214
}
147215
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.dependencyinjectiontypes;
2+
3+
import org.springframework.context.ApplicationContext;
4+
import org.springframework.context.support.ClassPathXmlApplicationContext;
5+
6+
public class ArticleFormatter {
7+
8+
@SuppressWarnings("resource")
9+
public static void main(String[] args) {
10+
ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml");
11+
ArticleWithSetterInjection article = (ArticleWithSetterInjection) context.getBean("articleWithSetterInjectionBean");
12+
String formattedArticle = article.format("This is a text !");
13+
14+
System.out.print(formattedArticle);
15+
}
16+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.dependencyinjectiontypes;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
5+
public class ArticleWithConstructorInjection {
6+
7+
private TextFormatter formatter;
8+
9+
@Autowired
10+
public ArticleWithConstructorInjection(TextFormatter formatter) {
11+
this.formatter = formatter;
12+
}
13+
14+
public String format(String text) {
15+
return formatter.format(text);
16+
}
17+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.baeldung.dependencyinjectiontypes;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
5+
public class ArticleWithSetterInjection {
6+
7+
private TextFormatter formatter;
8+
9+
public ArticleWithSetterInjection(TextFormatter formatter) {
10+
this.formatter = formatter;
11+
}
12+
13+
@Autowired
14+
public void setTextFormatter(TextFormatter formatter) {
15+
this.formatter = formatter;
16+
}
17+
18+
public String format(String text) {
19+
return formatter.format(text);
20+
}
21+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.baeldung.dependencyinjectiontypes;
2+
3+
public class TextFormatter {
4+
5+
public String format(String text) {
6+
return text.toUpperCase();
7+
}
8+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<beans xmlns="http://www.springframework.org/schema/beans"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
3+
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
4+
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
5+
xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
6+
7+
<context:annotation-config/>
8+
9+
<bean id="articleWithSetterInjectionBean"
10+
class="com.baeldung.dependencyinjectiontypes.ArticleWithSetterInjection">
11+
<constructor-arg ref="textFormatterBean" />
12+
</bean>
13+
14+
<bean id="articleWithConstructorInjectionBean"
15+
class="com.baeldung.dependencyinjectiontypes.ArticleWithConstructorInjection">
16+
<constructor-arg ref="textFormatterBean" />
17+
</bean>
18+
19+
20+
<bean id="textFormatterBean" class="com.baeldung.dependencyinjectiontypes.TextFormatter">
21+
</bean>
22+
23+
</beans>
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.baeldung.dependencyinjectiontypes;
2+
3+
import static org.junit.Assert.assertTrue;
4+
5+
import org.junit.Test;
6+
import org.springframework.context.ApplicationContext;
7+
import org.springframework.context.support.ClassPathXmlApplicationContext;
8+
9+
public class DependencyInjectionTest {
10+
11+
@Test
12+
public void givenAutowiredAnnotation_WhenSetOnSetter_ThenDependencyValid() {
13+
14+
ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml");
15+
ArticleWithSetterInjection article = (ArticleWithSetterInjection) context.getBean("articleWithSetterInjectionBean");
16+
17+
String originalText = "This is a text !";
18+
String formattedArticle = article.format(originalText);
19+
20+
assertTrue(originalText.toUpperCase().equals(formattedArticle));
21+
}
22+
23+
@Test
24+
public void givenAutowiredAnnotation_WhenSetOnConstructor_ThenDependencyValid() {
25+
26+
ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml");
27+
ArticleWithConstructorInjection article = (ArticleWithConstructorInjection) context.getBean("articleWithConstructorInjectionBean");
28+
29+
String originalText = "This is a text !";
30+
String formattedArticle = article.format(originalText);
31+
32+
assertTrue(originalText.toUpperCase().equals(formattedArticle));
33+
}
34+
35+
}

0 commit comments

Comments
 (0)