Code samples for spring @Async annotation.

This commit is contained in:
mgooty
2014-12-07 21:15:52 +05:30
parent b5cc62b50e
commit abbfc01105
6 changed files with 197 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
package org.baeldung.async;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.baeldung.async.config.SpringAsyncConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringAsyncConfig.class }, loader = AnnotationConfigContextLoader.class)
public class AsyncAnnotationExampleTest {
@Autowired
AsyncAnnotationExample asyncAnnotationExample;
@Test
public void testAsyncAnnotationForMethodsWithVoidReturnType() {
System.out.println("Start - invoking an asynchronous method. "
+ Thread.currentThread().getName());
asyncAnnotationExample.asyncMethodWithVoidReturnType();
System.out.println("End - invoking an asynchronous method. ");
}
@Test
public void testAsyncAnnotationForMethodsWithReturnType()
throws InterruptedException, ExecutionException {
System.out.println("Start - invoking an asynchronous method. "
+ Thread.currentThread().getName());
final Future<String> future = asyncAnnotationExample
.asyncMethodWithReturnType();
while (true) {
if (future.isDone()) {
System.out.println("Result from asynchronous process - "
+ future.get());
break;
}
System.out.println("Continue doing something else. ");
Thread.sleep(1000);
}
}
@Test
public void testAsyncAnnotationForMethodsWithConfiguredExecutor() {
System.out.println("Start - invoking an asynchronous method. ");
asyncAnnotationExample.asyncMethodWithConfiguredExecutor();
System.out.println("End - invoking an asynchronous method. ");
}
@Test
public void testAsyncAnnotationForMethodsWithException() throws Exception {
System.out.println("Start - invoking an asynchronous method. ");
asyncAnnotationExample.asyncMethodWithExceptions();
System.out.println("End - invoking an asynchronous method. ");
}
}