Using custom thread pool ThreadPoolTaskExecutor in springboot

Posted by dniezby on Mon, 11 Nov 2019 16:41:46 +0100

After java5, the thread has changed a lot. It is more convenient and powerful in use. Spring boot is further encapsulated.

    Let's take an example
   package com.executor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

import org.springframework.context.annotation.Configuration;
import
org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configurationbr/>@EnableAsync
public class ThreadConfig implements AsyncConfigurer {

@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(5);
    executor.setMaxPoolSize(15);
    executor.setThreadNamePrefix("Anno-Executor");
    executor.setQueueCapacity(25);
    executor.initialize();
    System.out.println("initialize complete ..");
    // Set rejection policy
    executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            // .....
            System.out.println("do somethings by myself ...");
        }
    });
    // Using predefined exception handling classes
    // executor.setRejectedExecutionHandler(new
    // ThreadPoolExecutor.CallerRunsPolicy());

    return executor;
}

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

}

package com.executor;

import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

@Service
public class SyncService {br/>@Async
public void hello() {
System.out.println("Get into service. . . ");
try {
Thread.sleep(3000);
System.out.println("3S After data processing..");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

@Async
public Future<String> asyncInvokeReturnFuture(int i) {
    System.out.println("Get into asyncInvokeReturnFuture..." + Thread.currentThread().getName());
    Future<String> future;
    try {
        Thread.sleep(3000);
        System.out.println("3S after asyncInvokeReturnFuture Data processing begins..");
        future = new AsyncResult<String>("success:" + i);
    } catch (InterruptedException e) {
        future = new AsyncResult<String>("error");
    }
    return future;
}

}

Run it

package com.executor;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;br/>@EnableAutoConfiguration
@RestController
br/>@SpringBootApplication
@EnableScheduling
br/>@EnableAsync
public class ExampleSync {

private final static Logger logger = LoggerFactory.getLogger(ExampleSync.class);
@Autowired
SyncService asyncService;

public static void main(String[] args) throws Exception {
    SpringApplication.run(ExampleSync.class, args);
}

 @GetMapping("/hello")
    public String hello(){
        System.out.println("Get into Controller. . . ");
        asyncService.hello();
        Future<String> future=asyncService.asyncInvokeReturnFuture(300);
        String s = null;
        try {
            s = future.get();
        } catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("Asynchronous method return value: "+s);
        return s;
    }

}

Enter Controller...
Enter service...
Enter asyncinvokereturnfuture... Anno executor2
Data processing starts after 3S..
After 3S, asyncInvokeReturnFuture data begins to be processed..
Asynchronous method return value: success:300
Enter Controller...
Enter service...
Enter asyncinvokereturnfuture... Anno executor3
Data processing starts after 3S..
After 3S, asyncInvokeReturnFuture data begins to be processed..
Asynchronous method return value: success:300

Topics: Java Spring