AsyncConfig.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package com.yihu.jw.care.config.async;
  2. import org.apache.tomcat.util.threads.ThreadPoolExecutor;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.scheduling.annotation.EnableAsync;
  6. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  7. import java.util.concurrent.Executor;
  8. /**
  9. * Created by chenweida on 2016.10.18.
  10. * 启用多綫程
  11. */
  12. @Configuration
  13. @EnableAsync
  14. public class AsyncConfig {
  15. /**
  16. * 如果池中的实际线程数小于corePoolSize,无论是否其中有空闲的线程,都会给新的任务产生新的线程
  17. */
  18. private int corePoolSize = 5;
  19. /**
  20. * 如果池中的线程数=maximumPoolSize,则有空闲线程使用空闲线程,否则新任务放入queueCapacity.
  21. * 设定 比 系统native thread个数要大的话,会优先抛出Java.lang.OutOfMemoryError: unable to create new native thread
  22. */
  23. private int maxPoolSize = 10;
  24. /**
  25. * 缓冲队列大小
  26. */
  27. private int queueCapacity = 100;
  28. /**
  29. * 线程池维护线程所允许的空闲时间 秒
  30. */
  31. private int keepAliveSeconds = 300;
  32. @Bean
  33. public Executor wlyyExecutor() {
  34. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  35. executor.setCorePoolSize(corePoolSize);
  36. executor.setMaxPoolSize(maxPoolSize);
  37. executor.setQueueCapacity(queueCapacity);
  38. executor.setKeepAliveSeconds(keepAliveSeconds);
  39. /** Reject策略预定义有四种:
  40. (1)ThreadPoolExecutor.AbortPolicy策略,是默认的策略,处理程序遭到拒绝将抛出运行时 RejectedExecutionException。
  41. (2)ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
  42. (3)ThreadPoolExecutor.DiscardPolicy策略,不能执行的任务将被丢弃.
  43. (4)ThreadPoolExecutor.DiscardOldestPolicy策略,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程).
  44. */
  45. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  46. executor.initialize();
  47. return executor;
  48. }
  49. }