Radu/bael 1265 junit updates (#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
This commit is contained in:
tamasradu 2017-11-06 03:46:29 +02:00 committed by maibin
parent 2e7d254adb
commit 90c2739563
8 changed files with 211 additions and 10 deletions

View File

@ -1,11 +1,18 @@
package com.baeldung.concurrent.executorservice;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
public class DelayedCallable implements Callable<String> {
private String name;
private long period;
private CountDownLatch latch;
public DelayedCallable(String name, long period, CountDownLatch latch) {
this(name, period);
this.latch = latch;
}
public DelayedCallable(String name, long period) {
this.name = name;
@ -16,9 +23,15 @@ public class DelayedCallable implements Callable<String> {
try {
Thread.sleep(period);
if (latch != null) {
latch.countDown();
}
} catch (InterruptedException ex) {
// handle exception
ex.printStackTrace();
Thread.currentThread().interrupt();
}
return name;

View File

@ -9,22 +9,91 @@ import java.util.List;
import java.util.concurrent.*;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.fail;
public class WaitingForThreadsToFinishTest {
private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishTest.class);
private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
threadPool.shutdown();
try {
if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
threadPool.shutdownNow();
}
} catch (InterruptedException ex) {
threadPool.shutdownNow();
Thread.currentThread().interrupt();
}
}
@Test
public void givenMultipleThreads_whenUsingCountDownLatch_thenMainShoudWaitForAllToFinish() {
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
try {
long startTime = System.currentTimeMillis();
// create a CountDownLatch that waits for the 2 threads to finish
CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
WORKER_THREAD_POOL.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
});
}
// wait for the latch to be decremented by the two threads
latch.await();
long processingTime = System.currentTimeMillis() - startTime;
assertTrue(processingTime >= 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
}
@Test
public void givenMultipleThreads_whenInvokeAll_thenMainThreadShouldWaitForAllToFinish() {
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
List<Callable<String>> callables = Arrays.asList(new DelayedCallable("fast thread", 100), new DelayedCallable("slow thread", 3000));
List<Callable<String>> callables = Arrays.asList(
new DelayedCallable("fast thread", 100),
new DelayedCallable("slow thread", 3000));
try {
long startProcessingTime = System.currentTimeMillis();
List<Future<String>> futures = WORKER_THREAD_POOL.invokeAll(callables);
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
try {
WORKER_THREAD_POOL.submit(new Callable<String>() {
@Override
public String call() throws Exception {
fail("This thread should have been rejected !");
Thread.sleep(1000000);
return null;
}
});
} catch (RejectedExecutionException ex) {
//
}
long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
assertTrue(totalProcessingTime >= 3000);
@ -39,9 +108,7 @@ public class WaitingForThreadsToFinishTest {
} catch (ExecutionException | InterruptedException ex) {
ex.printStackTrace();
}
WORKER_THREAD_POOL.shutdown();
}
}
@Test
@ -49,14 +116,14 @@ public class WaitingForThreadsToFinishTest {
CompletionService<String> service = new ExecutorCompletionService<>(WORKER_THREAD_POOL);
List<Callable<String>> callables = Arrays.asList(new DelayedCallable("fast thread", 100), new DelayedCallable("slow thread", 3000));
List<Callable<String>> callables = Arrays.asList(
new DelayedCallable("fast thread", 100),
new DelayedCallable("slow thread", 3000));
for (Callable<String> callable : callables) {
service.submit(callable);
}
WORKER_THREAD_POOL.shutdown();
try {
long startProcessingTime = System.currentTimeMillis();
@ -79,8 +146,9 @@ public class WaitingForThreadsToFinishTest {
} catch (ExecutionException | InterruptedException ex) {
ex.printStackTrace();
} finally {
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
}
}
@Test
@ -142,6 +210,6 @@ public class WaitingForThreadsToFinishTest {
e.printStackTrace();
}
WORKER_THREAD_POOL.shutdown();
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.dependencyinjectiontypes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ArticleFormatter {
@SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml");
ArticleWithSetterInjection article = (ArticleWithSetterInjection) context.getBean("articleWithSetterInjectionBean");
String formattedArticle = article.format("This is a text !");
System.out.print(formattedArticle);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.dependencyinjectiontypes;
import org.springframework.beans.factory.annotation.Autowired;
public class ArticleWithConstructorInjection {
private TextFormatter formatter;
@Autowired
public ArticleWithConstructorInjection(TextFormatter formatter) {
this.formatter = formatter;
}
public String format(String text) {
return formatter.format(text);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.dependencyinjectiontypes;
import org.springframework.beans.factory.annotation.Autowired;
public class ArticleWithSetterInjection {
private TextFormatter formatter;
public ArticleWithSetterInjection(TextFormatter formatter) {
this.formatter = formatter;
}
@Autowired
public void setTextFormatter(TextFormatter formatter) {
this.formatter = formatter;
}
public String format(String text) {
return formatter.format(text);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.dependencyinjectiontypes;
public class TextFormatter {
public String format(String text) {
return text.toUpperCase();
}
}

View File

@ -0,0 +1,23 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
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">
<context:annotation-config/>
<bean id="articleWithSetterInjectionBean"
class="com.baeldung.dependencyinjectiontypes.ArticleWithSetterInjection">
<constructor-arg ref="textFormatterBean" />
</bean>
<bean id="articleWithConstructorInjectionBean"
class="com.baeldung.dependencyinjectiontypes.ArticleWithConstructorInjection">
<constructor-arg ref="textFormatterBean" />
</bean>
<bean id="textFormatterBean" class="com.baeldung.dependencyinjectiontypes.TextFormatter">
</bean>
</beans>

View File

@ -0,0 +1,35 @@
package com.baeldung.dependencyinjectiontypes;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DependencyInjectionTest {
@Test
public void givenAutowiredAnnotation_WhenSetOnSetter_ThenDependencyValid() {
ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml");
ArticleWithSetterInjection article = (ArticleWithSetterInjection) context.getBean("articleWithSetterInjectionBean");
String originalText = "This is a text !";
String formattedArticle = article.format(originalText);
assertTrue(originalText.toUpperCase().equals(formattedArticle));
}
@Test
public void givenAutowiredAnnotation_WhenSetOnConstructor_ThenDependencyValid() {
ApplicationContext context = new ClassPathXmlApplicationContext("dependencyinjectiontypes-context.xml");
ArticleWithConstructorInjection article = (ArticleWithConstructorInjection) context.getBean("articleWithConstructorInjectionBean");
String originalText = "This is a text !";
String formattedArticle = article.format(originalText);
assertTrue(originalText.toUpperCase().equals(formattedArticle));
}
}