Home > AI > Backend > SpringBoot >

@Async with thread pool

Add dependency

<dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>11.0.2</version>
        </dependency>

Code

@SpringBootApplication
@EnableAsync
public class Demo12Application {

	public static void main(String[] args) {

		SpringApplication.run(Demo12Application.class, args);
	}
}


@Configuration
 class ThreadPoolExecutorConfig {
    private static final int THREADS = Runtime.getRuntime().availableProcessors() + 1;

    final ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat("async-task-name-%d")
            .setDaemon(true)
            .build();


    // pool name
    @Bean("taskExecutor")
    public Executor taskExecutor() {
        return new ThreadPoolExecutor(THREADS,
                2 * THREADS,
                5,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1024),
                threadFactory, (r, executor) -> {
            //  Print logs, add monitoring, etc.
            System.out.println("task is rejected!");
        });
    }
}



@Service
 class TaskServer {

    @Async("taskExecutor")
    public void doTaskA() throws InterruptedException {
        System.out.println("MsgServer send A thread name->" + Thread.currentThread().getName());
        Long startTime = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(2);

        Long endTime = System.currentTimeMillis();
        System.out.println("MsgServer send A time-consuming:" + (endTime- startTime));
    }

    @Async("taskExecutor")
    public void doTaskB() throws InterruptedException {
        System.out.println("MsgServer send B thread name->" + Thread.currentThread().getName());
        Long startTime = System.currentTimeMillis();
        TimeUnit.SECONDS.sleep(2);
        Long endTime = System.currentTimeMillis();
        System.out.println("MsgServer send B time-consuming:" + (endTime- startTime));
    }
}


@RestController
 class HelloController {

    @Resource
    private TaskServer taskServer;

    @GetMapping("/async")
    public String testAsync() throws Exception {
        System.out.println("Main thread name -->" + Thread.currentThread().getName());
        taskServer.doTaskA();
        taskServer.doTaskB();
        return "Hello World";
    }
}

Leave a Reply