Verification of the reasons why Executors were disabled by Ali

Alibaba Development Manual mentioned in the programming protocol-concurrent processing:
[Mandatory] Thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor. This way of processing allows students to write more clear rules of thread pool operation and avoid Risk of resource exhaustion.
Description: The disadvantages of the thread pool object returned by Executors are as follows: 1) FixedThreadPool and SingleThreadPool: The allowed request queue length is Integer.MAX_VALUE, which may accumulate a large number of requests, resulting in OOM. 2) CachedThreadPool: The number of allowed creation threads is Integer.MAX_VALUE, which may create a large number of threads, resulting in OOM.
Let's verify with the program, the JVM parameters used are: -Xmx5m -Xms5m (can be set in VM options in idea). The relevant principles of the program are explained in the comments:

package com.ebao.threadpool;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Test;

/**
 * @title: ExecutorsTest
 * @projectName demo1
 * @description: 验证Executors工具类的几个API的OOM问题
 * @date 2020/4/188:59
 */
public class ExecutorsTest {

  public static void main(String[] args) {
    /**
     * newFixedThreadPool使用指定参数1为核心和最大线程数,使用的任务队列LinkedBlockingQueue
     * 默认队列长度为Integer.MAX_VALUE,可以认为是无界的
     */
    ExecutorService executorService = Executors.newSingleThreadExecutor();
//    ExecutorService executorService = Executors.newFixedThreadPool(1);//测试newFixedThreadPool时打开此注释
//    ExecutorService executorService = Executors.newCachedThreadPool();//测试newCachedThreadPool时打开此注释
    /**
     * 使用一个无限循环,不停创建和提交任务,因为任务中也是在进行无限循环(自旋),所以线程池中线程无法复用
     */
    for (; ; ) {
      executorService.submit(new MyTask());
    }
  }
}

class MyTask implements Callable<String> {

  //使用一个大小为1024=1m的字节数组让每个任务占用内存比较大,容易验证OOM情况
  byte[] byteArray = new byte[2048];

  @Override
  public String call() throws Exception {
    System.out.println("开始执行任务");
    /**
     * 使用一个无限循环一直自旋,也就是该任务一直占用一个线程,不会把线程放回线程池共其他任务复用
     */
    for (; ; ) {
    }
  }
}



The results are as follows:
Insert picture description here

Published 14 original articles · Like 3 · Visitor 925

Guess you like

Origin blog.csdn.net/sjz88888/article/details/105593385