IEAD中加入阿里的代码检查插件后Executors提示需手动创建

转自:https://blog.csdn.net/w605283073/article/details/80259493

最近了解一下线程池,下载其中的代码并运行。

https://howtodoinjava.com/core-java/multi-threading/when-to-use-countdownlatch-java-concurrency-example-tutorial/

其中ApplicationStartupUtil这个类


  
  
  1. package com.chujianyun;
  2. import com.chujianyun.verifier.BaseHealthChecker;
  3. import com.chujianyun.verifier.CacheHealthChecker;
  4. import com.chujianyun.verifier.DatabaseHealthChecker;
  5. import com.chujianyun.verifier.NetworkHealthChecker;
  6. import java.util.concurrent.*;
  7. public class ApplicationStartupUtil
  8. {
  9. private static BlockingQueue <Runnable> services;
  10. private static CountDownLatch latch;
  11. private ApplicationStartupUtil()
  12. {
  13. }
  14. private final static ApplicationStartupUtil INSTANCE = new ApplicationStartupUtil();
  15. public static ApplicationStartupUtil getInstance()
  16. {
  17. return INSTANCE;
  18. }
  19. public static boolean checkExternalServices() throws Exception
  20. {
  21. latch = new CountDownLatch(3);
  22. services = new ArrayBlockingQueue <>(3);
  23. services.add(new NetworkHealthChecker(latch));
  24. services.add(new CacheHealthChecker(latch));
  25. services.add(new DatabaseHealthChecker(latch));
  26. ExecutorService executorService = Executors.newFixedThreadPool(services.size());
  27. for(final Runnable v : services)
  28. {
  29. executorService.execute(v);
  30. }
  31. latch.await();
  32. for(final Runnable v : services)
  33. {
  34. BaseHealthChecker baseHealthChecker = (BaseHealthChecker) v;
  35. if( ! baseHealthChecker.isServiceUp())
  36. {
  37. return false;
  38. }
  39. }
  40. return true;
  41. }
  42. }

其中有下面代码:

ExecutorService executorService = Executors.newFixedThreadPool(services.size());
  
  

由于IDEA安装了阿里的Java编程规范检查插件,提示让手动创建线程池

1、修改代码

查看newFixedThreadPool函数源码:


  
  
  1. /**
  2. * Creates a thread pool that reuses a fixed number of threads
  3. * operating off a shared unbounded queue. At any point, at most
  4. * {@code nThreads} threads will be active processing tasks.
  5. * If additional tasks are submitted when all threads are active,
  6. * they will wait in the queue until a thread is available.
  7. * If any thread terminates due to a failure during execution
  8. * prior to shutdown, a new one will take its place if needed to
  9. * execute subsequent tasks. The threads in the pool will exist
  10. * until it is explicitly {@link ExecutorService#shutdown shutdown}.
  11. *
  12. * @param nThreads the number of threads in the pool
  13. * @return the newly created thread pool
  14. * @throws IllegalArgumentException if {@code nThreads <= 0}
  15. */
  16. public static ExecutorService newFixedThreadPool(int nThreads) {
  17. return new ThreadPoolExecutor(nThreads, nThreads,
  18. 0L, TimeUnit.MILLISECONDS,
  19. new LinkedBlockingQueue<Runnable>());
  20. }

得知该函数最终调用的还是ThreadPoolExecutor构造方法。

因此上面一句可以改成:


  
  
  1. int size = services.size();
  2. ExecutorService executorService = new ThreadPoolExecutor(size,size,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue <Runnable>());

但是又有提示,建议要为线程池中的线程设置名称:

仅此在构造方法后加入TreadFactory,大功告成 


  
  
  1. ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
  2. int size = services.size();
  3. ExecutorService executorService = new ThreadPoolExecutor(size,size,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue <Runnable>(),namedThreadFactory);

2、为什么要这么做呢?

我们参考阿里巴巴的Java开发手册内容:

8.   【强制】线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。

说明:Executors各个方法的弊端:

1)    newFixedThreadPool和newSingleThreadExecutor:  主要问题是堆积的请求处理队列可能会耗费非常大的内存,甚至OOM。

2)    newCachedThreadPool和newScheduledThreadPool:  主要问题是线程数最大数是Integer.MAX_VALUE,可能会创建数量非常多的线程,甚至OOM。

9. 【强制】创建线程或线程池时请指定有意义的线程名称,方便出错时回溯。

我在此简单进一步解读一下:

[1] newFixedThreadPool和newSingleThreadExecutor 由于最后一个参数即工作队列是:


  
  
  1. /**
  2. * Creates a thread pool that reuses a fixed number of threads
  3. * operating off a shared unbounded queue. At any point, at most
  4. * {@code nThreads} threads will be active processing tasks.
  5. * If additional tasks are submitted when all threads are active,
  6. * they will wait in the queue until a thread is available.
  7. * If any thread terminates due to a failure during execution
  8. * prior to shutdown, a new one will take its place if needed to
  9. * execute subsequent tasks. The threads in the pool will exist
  10. * until it is explicitly {@link ExecutorService#shutdown shutdown}.
  11. *
  12. * @param nThreads the number of threads in the pool
  13. * @return the newly created thread pool
  14. * @throws IllegalArgumentException if {@code nThreads <= 0}
  15. */
  16. public static ExecutorService newFixedThreadPool(int nThreads) {
  17. return new ThreadPoolExecutor(nThreads, nThreads,
  18. 0L, TimeUnit.MILLISECONDS,
  19. new LinkedBlockingQueue<Runnable>());
  20. }

链表类型的阻塞队列,而我们看其构造函数发现,默认队列大小是整数的最大值!!


  
  
  1. /**
  2. * Creates a {@code LinkedBlockingQueue} with a capacity of
  3. * {@link Integer#MAX_VALUE}.
  4. */
  5. public LinkedBlockingQueue() {
  6. this(Integer.MAX_VALUE);
  7. }
  8. /**
  9. * Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
  10. *
  11. * @param capacity the capacity of this queue
  12. * @throws IllegalArgumentException if {@code capacity} is not greater
  13. * than zero
  14. */
  15. public LinkedBlockingQueue(int capacity) {
  16. if (capacity <= 0) throw new IllegalArgumentException();
  17. this.capacity = capacity;
  18. last = head = new Node<E>( null);
  19. }

所以如果请求太多,队列很可能就耗费内存非常大导致OOM.

但是他们的线程数是固定的,而且一般不会太大,所以不会因为创建过多线程而导致OOM。

[2]newCachedThreadPool和newScheduledThreadPool:


  
  
  1. /**
  2. * Creates a thread pool that creates new threads as needed, but
  3. * will reuse previously constructed threads when they are
  4. * available. These pools will typically improve the performance
  5. * of programs that execute many short-lived asynchronous tasks.
  6. * Calls to {@code execute} will reuse previously constructed
  7. * threads if available. If no existing thread is available, a new
  8. * thread will be created and added to the pool. Threads that have
  9. * not been used for sixty seconds are terminated and removed from
  10. * the cache. Thus, a pool that remains idle for long enough will
  11. * not consume any resources. Note that pools with similar
  12. * properties but different details (for example, timeout parameters)
  13. * may be created using {@link ThreadPoolExecutor} constructors.
  14. *
  15. * @return the newly created thread pool
  16. */
  17. public static ExecutorService newCachedThreadPool() {
  18. return new ThreadPoolExecutor( 0, Integer.MAX_VALUE,
  19. 60L, TimeUnit.SECONDS,
  20. new SynchronousQueue<Runnable>());
  21. }

其中第最大线程池大小是整数的最大值,因此线程可能不断创建,乃至到整数的最大值个线程,很容易导致OOM.

其中工作队列使用的是 SynchronousQueue<E>

源码头部的注释中有说明


  
  
  1. * A { @linkplain BlockingQueue blocking queue} in which each insert
  2. * operation must wait for a corresponding remove operation by another
  3. * thread, and vice versa. A synchronous queue does not have any
  4. * internal capacity, not even a capacity of one. You cannot
  5. * { @code peek} at a synchronous queue because an element is only
  6. * present when you try to remove it; you cannot insert an element
  7. * (using any method) unless another thread is trying to remove it;
  8. * you cannot iterate as there is nothing to iterate. The
  9. * <em>head</em> of the queue is the element that the first queued
  10. * inserting thread is trying to add to the queue; if there is no such
  11. * queued thread then no element is available for removal and
  12. * { @code poll()} will return { @code null}. For purposes of other
  13. * { @code Collection} methods ( for example { @code contains}), a
  14. * { @code SynchronousQueue} acts as an empty collection. This queue
  15. * does not permit { @code null} elements.

可以看出

A {@linkplain BlockingQueue blocking queue} in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa.

该类型的阻塞队列每一个插入操作必须等待对应的元素被另一个线程所移除,反之亦然。

因此阻塞队列不会无限拓展而导致OOM。

因此我们理解一些原则的时候,学习的时候多注重源码分析非常有必要,其他细节有待以后深入研究。

参考文章:http://www.crazyant.net/2124.html

最近了解一下线程池,下载其中的代码并运行。

猜你喜欢

转载自blog.csdn.net/qq_31001889/article/details/85005180