package com.bonus.canteen.core.starter.threadpool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class AsyncConfig {
   @Bean({"yunshitangTaskExecutor"})
   public AsyncTaskExecutor taskExecutor() {
      int i = Runtime.getRuntime().availableProcessors();
      ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
      taskExecutor.setMaxPoolSize(i * 2);
      taskExecutor.setCorePoolSize(i * 2);
      taskExecutor.setThreadNamePrefix("async-yst-yunshitang-pool");
      taskExecutor.setQueueCapacity(1000);
      taskExecutor.setKeepAliveSeconds(60);
      taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
      taskExecutor.setAwaitTerminationSeconds(60);
      taskExecutor.setTaskDecorator(new CleanTenantIdTaskDecorator());
      taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
      taskExecutor.initialize();
      return taskExecutor;
   }
}
