Java Concurrency - Ali architect is how clever use of the thread pool!

Java Concurrency - Ali architect is how clever use of the thread pool!

First, create a thread

1. Create a generic object, but the JVM heap allocation in a memory of it

2. Create a thread, you need to call the operating system kernel API, then the operating system needs to allocate resources for a series of threads, high cost

  • A thread is a heavyweight object should avoid frequently create and destroy, thread pool scheme

Second, the general pool of resources

// 假设Java线程池采用一般意义上池化资源的设计方法
class ThreadPool {
    // 获取空闲线程
    Thread acquire() {
    }
    // 释放线程
    void release(Thread t) {
    }
}
// 期望的使用
ThreadPool pool;
Thread T1 = pool.acquire();
// 传入Runnable对象
T1.execute(() -> {
    // 具体业务逻辑
});

Third, the producer - consumer model

Design industry thread pool, commonly used by the producer - consumer model, the consumer is the producer thread pool, thread pool itself is a consumer

public class MyThreadPool {
    // 工作线程负责消费任务并执行任务
    class WorkerThread extends Thread {
        @Override
        public void run() {
            // 循环取任务并执行
            while (true) {
                Runnable task = null;
                try {
                    task = workQueue.take();
                } catch (InterruptedException e) {
                }
                task.run();
            }
        }
    }

    // 利用阻塞队列实现生产者-消费者模式
    private BlockingQueue<Runnable> workQueue;
    // 内部保存工作线程
    List<WorkerThread> threads = new ArrayList<>();

    public MyThreadPool(int poolSize, BlockingQueue<Runnable> workQueue) {
        this.workQueue = workQueue;
        for (int i = 0; i < poolSize; i++) {
            WorkerThread work = new WorkerThread();
            work.start();
            threads.add(work);
        }
    }

    // 提交任务
    public void execute(Runnable command) throws InterruptedException {
        workQueue.put(command);
    }

    public static void main(String[] args) throws InterruptedException {
        // 创建有界阻塞队列
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(2);
        // 创建线程池
        MyThreadPool pool = new MyThreadPool(10, workQueue);
        // 提交任务
        pool.execute(() -> {
            System.out.println("hello");
        });
    }
}

Four, Java thread pool

Ⅰ. ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler)

// 让所有线程都支持超时,如果线程池很闲,那么将撤销所有线程
public void allowCoreThreadTimeOut(boolean value)

1.corePoolSize: The minimum number of threads in the thread pool to maintain the

2.maximumPoolSize: The maximum number of threads in the thread pool created

3.keepAliveTime & unit

  • If a thread has been idle keepAliveTime & unit, and the number of threads in the thread pool greater than corePoolSize, then the idle thread will be recovered

4.workQueue: Work Queue

5.threadFactory: How to create a custom thread

6.handler

  • All threads in the pool are busy, and the work queue was full (bounded work queue is a queue), then submit the task, the thread pool will reject
  • CallerRunsPolicy: thread submit themselves to the task of performing the task
  • AbortPolicy: default deny policy, throw RejectedExecutionException
  • DiscardPolicy: discards the task, no exception is thrown
  • DiscardOldestPolicy: discard the oldest task, then the new task is added to the work queue

Ⅱ. Executors

1. does not recommend the use of Executors, because a lot of the default method provided using Executors ××× queue LinkedBlockingQueue

2. In the case of high load, ××× queue easily lead to OOM, while the OOM will cause all requests can not be processed

3. It is strongly recommended to use a bounded queue

Ⅲ. Rejection policy

1. Use the bounded queue, when too many tasks, the thread pool will trigger rejection policy

2. Thread Pool default deny policy will throw RejectedExecutionException, which is abnormal, it is easy to overlook when developing a runtime

3. If the task thread pool is important, you can customize denial policy

Ⅳ. Exception Handling

When submitting method Task 1. Use ThreadPoolExecutor.execute (), when you run the task exception occurs during execution

  • Thread will result in termination of tasks, and without any notice

2. Therefore, the safest way is to catch all exceptions and handling

try {
    // 业务逻辑
} catch (RuntimeException x) {
    // 按需处理
} catch (Throwable x) {
    // 按需处理
}

Written in the last

Java Concurrency - Ali architect is how clever use of the thread pool!

Guess you like

Origin blog.51cto.com/14409778/2412806