springboot 우아 한 스 레 드 풀 사용

두 걸음 만 간단하게 하면 된다.
정의 실행 자

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;


@Slf4j
@Configuration
public class AsyncThreadPoolConfiguration {

    //  CPU     
    private int maximumPoolSizePerCPU;
	//      
    private int blockingCapacity;

    @Bean
    public Executor asyncExecutor() {
        //      CPU  
        int cpuCores = Runtime.getRuntime().availableProcessors();
        //fixed thread pool (core == max)
        return new ThreadPoolExecutor(
                maximumPoolSizePerCPU * cpuCores,
                maximumPoolSizePerCPU * cpuCores,
                0,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(blockingCapacity),
                new FirstInFirstRejectPolicy());
    }

    private class LogRejectPolicy implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            log.warn("reject a task");
        }

    }
	
	//       
    private class FirstInFirstRejectPolicy implements RejectedExecutionHandler {

        public FirstInFirstRejectPolicy() {
        }

        /**
         * Obtains and ignores the next task that the executor
         * would otherwise execute, if one is immediately available,
         * and then retries execution of task r, unless the executor
         * is shut down, in which case task r is instead discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                //warn
                log.warn("reject first task of queue");
                //exec
                e.execute(r);
            }
        }
    }
}

새 작업 클래스

import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Function;

/**
 * Copyright© 2019
 *
 * @author yuhui.xie
 * @date 2019/11/1
 */
@Component
public class AsyncTask {
    private final Executor asyncExecutor;

    public AsyncTask(Executor asyncExecutor) {
        this.asyncExecutor = asyncExecutor;
    }

    public void run(Runnable runnable) {
        CompletableFuture.runAsync(runnable, asyncExecutor);
    }

    public void run(Runnable runnable, Function<Throwable, ? extends Void> exceptionHandler) {
        CompletableFuture.runAsync(runnable, asyncExecutor).exceptionally(exceptionHandler);
    }

    public void submit(Runnable runnable) {
        asyncExecutor.execute(runnable);
    }
}


쓰다
 asyncTask.run(() ->
               //TODO
                ));

좋은 웹페이지 즐겨찾기