0

I have a long running service method which I'm starting with a rest call from the controller.

Service:

@Service
public class TestServiceImpl implements TestService {

    @Override
    public void doSomething() {
        System.out.println("1: " + DateTime.now());
        runLongTask();
        System.out.println("2: " + DateTime.now());

    }

    @Async
    private runLongTask() {
        System.out.println("Test");
        Thread.sleep(10000);
        System.out.println("3: "+ DateTime.now());
    }
}

In my Application.java I have

private int poolSize = 10;

private int queueCapacity = 10;

@Bean(name="taskExecutor")
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setMaxPoolSize(this.poolSize);
    taskExecutor.setQueueCapacity(this.queueCapacity);
    taskExecutor.afterPropertiesSet();
    return new ThreadPoolTaskExecutor();
}

And of course I have the @EnableAsync Annotation at my Application.java class

So I would Expect that the output is something like that:

1: 2015-10-23 11:20:00
2: 2015-10-23 11:20:01
Test
3: 2015-10-23 11:20:11
Cœur
  • 37,241
  • 25
  • 195
  • 267
Alexander Kiefer
  • 546
  • 1
  • 13
  • 30

2 Answers2

10

you need to call method from different class to use annotations like @Async or @Transactional. Spring do this stuff by wrapping annotated methods by proxy. In case when you call method from the same class then it has no effect.

hi_my_name_is
  • 4,894
  • 3
  • 34
  • 50
1

According to the documentation you need to implement the AsyncConfigurer interface in your Configuration class (in this case I assume is your Application instance) to override the SimpleAsyncTaskExecutor.

A full example is also shown in the documentation:

 @Configuration
 @EnableAsync
 public class AppConfig implements AsyncConfigurer {

 @Bean
 public MyAsyncBean asyncBean() {
     return new MyAsyncBean();
 }

 @Override
 public Executor getAsyncExecutor() {
     ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
     executor.setCorePoolSize(7);
     executor.setMaxPoolSize(42);
     executor.setQueueCapacity(11);
     executor.setThreadNamePrefix("MyExecutor-");
     executor.initialize();
     return executor;
 }

 @Override
 public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
         return MyAsyncUncaughtExceptionHandler();
 }
}

HTH,

Jose Luis

jbarrueta
  • 4,907
  • 2
  • 20
  • 21