JUC thread pool depth analysis of plane

JDK provides four default thread pool: SingleThreadExecutor, FiexdThreadPool, CachedThreadPool, ScheduledThreadPoolExecutor.

This article will first use the past three thread pool began to explain, then over to the thread pool parameters, refused to explain the terms of a comprehensive strategy, herself, according to a parameter structure

Thread Pool.

SingleThreadExecutor

    public static void singleThreadExecutorTest() {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        
        executorService.execute(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executorService.execute(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executorService.execute(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        
        try {
            Thread.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
    }

The code is to use a size Exectors tools created for the thread pool 1, and create three tasks submitted to this thread execution, execution of each task needs second. Therefore, from the operating results we can clearly see three task can execute only one thread.

FiexdThreadPool

public static void fixedThreadPoolTest() {
        ExecutorService service = Executors.newFixedThreadPool(2);
        service.execute(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        service.execute(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        service.execute(()->{
            
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        service.shutdown();
    }

The code is to use Exectors tools to create a thread pool size 2, and create three tasks submitted to this thread execution, execution of each task needs second. From the results can be seen that the first thread of execution together two seconds, before the second thread execution third seconds.

CachedThreadPool

public static void cachedThreadPoolTest() {
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        service.execute(()->{
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        service.execute(()->{
            
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        service.shutdown();
    }

The code is a size used Exectors tools created for Integer.MAX_VALUE thread pool, and create three tasks submitted to this thread execution, execution of each task needs second. The results can be seen from three threads to perform together.

Principle Analysis

Configuration parameters needed SingThreadExecutor

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

Configuration parameters needed FiexdThreadPool

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

Configuration parameters needed CachedThreadPool

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

We can see by the above source pool constructed three threads, thread pool that creates all the time through the creation ThreadPoolExecutor object, creating ThreadPoolExecutor need five parameters , then what is it these five parameters, we continue to track the source

Construction ThreadPoolExecutor object requires parameters

 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

Here you can see the object needs to generate ThreadPoolExecutor pass configuration parameters to their five parameters, but this is actually the following seven parameters. That there are two parameters are already fixed good. We track go in and see the seven parameters

ThreadPoolExecutor constructor Source

To highlight came here, following the code is being created constructor Barbara ThreadPoolExecutor source object. We can see a total of seven parameters, let's talk about the seven parameters

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

 

Create a thread pool needs seven parameters

int corePoolSize: Permanent core number of threads

int maximumPoolSize: maximum number of threads

long keepAliveTime: survival time in addition to permanent additional thread thread

TimeUnit unit: survival time units

BlockingQueue <Runnable> workQueue: Task Queue

ThreadFactory threadFactory: Create a thread factory

RejectedExecutionHandler handler: deny policy

Let's familiar about these seven parameters, then we have to explain these seven parameters from the workflow thread pool

Thread Pool workflow

When the thread pool just created it was empty, at this time no thread. When the main thread to thread pool which added the task will begin to create a thread

1 main thread to thread pool add tasks and found that the core thread is empty, create a core mission thread

2 With the main thread to thread pool plus mission, core threads are occupied, then the task will be placed in the job queue

3 With the main thread to thread pool continues to increase, the task queue is also full, the thread pool will create additional threads to perform tasks.

4 main thread continues to add tasks, task queue is full, the core thread full. Additional core thread thread + = total number of threads that additional thread was full, and this time it will refuse to execute strategy.

4 to 5 if no less extreme, with the execution of the task, the task queue less and less, until there is no, then the additional thread destroyed after waiting keepaliveTime time, leaving only the core thread pool threads exist.

I believe knows the process after the above seven parameters are what we also know, the thing to note here is the core number of threads is included in the total number of threads inside.

JDK comes to talk about the shortcomings of the thread pool

We can see from the above, JDK comes SingleThreadExecutor, FixedThreadPool are based LinkedBlockingQueue blocking queue as a task queue, as is a LinkedBlockingQueue

Integer.MAX_VALUE size of blocking queue, thus blocking the main thread in the queue will not add full-time job, that is not trigger rejection policy, may lead to sustained add tasks triggered OOM. The CachedThreadPool

The maximum number of threads to Integer.MAX_VALUE, wireless will create a thread, a task to create a thread, the thread may lead to too much lead OOM create all of our own construction parameters are generally create thread pool.

Four rejection policy

AbortPolicy: When the task queue threads and the maximum number of threads also add tasks, then a direct throw an exception that prevents the program runs

CallerRunsPolicy: When the task queue threads and the maximum number of threads added task will not throw an exception and abandon the task, but the task will be rolled back to the caller.

DiscardOldestPolicy: When the task queue threads and the maximum number of threads will also add words task queue task longest waiting a task discarded and then add a new task

DiscardPolicy: direct abandon the task. No treatment nor Throws

Construct their own thread pool

The core number of threads in the thread pool for 2, maximum number of threads is 5, extra thread survival time of 60 seconds, blocking queue size is 3, the default thread factory default deny policy, that Throws

Therefore, the continuous thread pool can provide up to eight tasks, is likely to trigger more than eight deny policy, Throws

public static void myThreadPool() {
        
        ExecutorService threadPool = new ThreadPoolExecutor(2, 
                5,
                60L,
                TimeUnit.SECONDS, 
                new LinkedBlockingQueue<>(3), 
                Executors.defaultThreadFactory(), 
                new ThreadPoolExecutor.AbortPolicy());
        
        for(int i=0;i<8;i++) {
            threadPool.execute(()->{
                System.out.println(Thread.currentThread().getName());
            });
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadPool.shutdown();
    }

How to choose the thread pool parameters

CPU-intensive: CPU-intensive CPU usage rate, has been at work, less idle time, so the maximum number of threads to the best CPU core number +1

IO-intensive: IO-intensive most of the time doing IO operation, CPU idle time and more, the maximum number of threads to the best CPU core number * 2.

Guess you like

Origin www.cnblogs.com/czsy/p/10943101.html