Executors of the thread pool

Executors of the thread pool + interview questions

Create a thread pool is divided into two ways: ThreadPoolExecutor and Executors, on a study of the ThreadPoolExecutor of use, this section focuses Executors of view is how to create a thread pool.
Executors can create the following six thread pool.

  • FixedThreadPool (n): to create a number of fixed thread pool beyond the idle thread waiting task in the queue, it can be used to control the maximum number of concurrent programs.
  • CachedThreadPool (): a short time a lot of work thread pool will produce according to the number of tasks corresponding thread, and the thread tries to cache for reuse, limit 60 seconds if not used, it will be removed cache.
  • SingleThreadExecutor (): Creates a single-threaded thread pool.
  • ScheduledThreadPool (n): to create a number of fixed thread pool, support the execution timing or periodic tasks.
  • SingleThreadScheduledExecutor (): This thread pool is single-threaded newScheduledThreadPool.
  • WorkStealingPool (n): Java 8 new method of creating a thread pool, when creating if any parameter is not set, the number of processors places the current machine as the number of threads, the thread pool will parallel processing tasks, the execution order can not be guaranteed.

The following are more specific code run using six kinds of thread pool.

FixedThreadPool use

Create a fixed number of thread pools, specific examples are as follows:

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 3; i++) {
    fixedThreadPool.execute(() -> {
        System.out.println("CurrentTime - " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}

The above program execution results are as follows:

CurrentTime - 2019-06-27 20:58:58

CurrentTime - 2019-06-27 20:58:58

CurrentTime - 2019-06-27 20:58:59

According to the results can be seen, newFixedThreadPool (2) really creates two threads, after performing a round (two times), stopped for a second, with the idle thread, before the implementation of the third.

CachedThreadPool use

According to the actual needs with caching feature to automatically create a thread pool, the specific code as follows:

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
    cachedThreadPool.execute(() -> {
        System.out.println("CurrentTime - " +
                           LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}

The above program execution results are as follows:

CurrentTime - 2019-06-27 21:24:46

CurrentTime - 2019-06-27 21:24:46

CurrentTime - 2019-06-27 21:24:46

CurrentTime - 2019-06-27 21:24:46

CurrentTime - 2019-06-27 21:24:46

CurrentTime - 2019-06-27 21:24:46

CurrentTime - 2019-06-27 21:24:46

CurrentTime - 2019-06-27 21:24:46

CurrentTime - 2019-06-27 21:24:46

CurrentTime - 2019-06-27 21:24:46

According to the results can be seen, newCachedThreadPool creates multiple threads in a short time to process the corresponding task, and try to cache them for reuse.

SingleThreadExecutor 使用

Create a single thread of the thread pool, the specific code as follows:

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 3; i++) {
    singleThreadExecutor.execute(() -> {
        System.out.println("CurrentTime - " +
                           LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}

The above program execution results are as follows:

CurrentTime - 2019-06-27 21:43:34

CurrentTime - 2019-06-27 21:43:35

CurrentTime - 2019-06-27 21:43:36

ScheduledThreadPool 使用

Create a periodic task can execute thread pool, the specific code as follows:

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
scheduledThreadPool.schedule(() -> {
    System.out.println("ThreadPool:" + LocalDateTime.now());
}, 1L, TimeUnit.SECONDS);
System.out.println("CurrentTime:" + LocalDateTime.now());

The above program execution results are as follows:

CurrentTime:2019-06-27T21:54:21.881

ThreadPool:2019-06-27T21:54:22.845

According to the results can be seen after one second we set the task execution into effect.

SingleThreadScheduledExecutor 使用

Create a periodic task can perform single-threaded pools, the specific code as follows:

ScheduledExecutorService singleThreadScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
singleThreadScheduledExecutor.schedule(() -> {
    System.out.println("ThreadPool:" + LocalDateTime.now());
}, 1L, TimeUnit.SECONDS);
System.out.println("CurrentTime:" + LocalDateTime.now());

WorkStealingPool 使用

Java 8 to create the new thread pool manner, based on the current number of PC CPU processor generates a corresponding number of thread pool, using the following code:

ExecutorService workStealingPool = Executors.newWorkStealingPool();
for (int i = 0; i < 5; i++) {
    int finalNumber = i;
    workStealingPool.execute(() -> {
        System.out.println("I:" + finalNumber);
    });
}
Thread.sleep(5000);

The above program execution results are as follows:

I:0

I:3

I:2

I:1

I:4

The execution results can be seen, newWorkStealingPool parallel processing tasks, and the execution order can not be guaranteed.

ThreadPoolExecutor VS Executors

ThreadPoolExecutor and Executors are used to create a thread pool, which ThreadPoolExecutor create a thread pool of relatively traditional way, but Executors provides more thread pool type (6 kinds), but unfortunately the news is not recommended in the actual development to create a thread pool using Executors way.

Coincidentally "Ali Baba Java Development Manual" in the same way prescribed for creating a thread pool, as follows:

Executors thread pool are not allowed to create, but by ThreadPoolExecutor way, this approach allows readers to write operating rules clearer thread pool, to avoid the risk of resource depletion.

Description: Executors malpractice thread pool objects returned as follows:

1)FixedThreadPool 和 SingleThreadPool:

The request queue length allowed Integer.MAX_VALUE, may accumulate a large number of requests, thereby causing OOM.

2)CachedThreadPool 和 ScheduledThreadPool:

The number of threads created to allow Integer.MAX_VALUE, may create a large number of threads, resulting OOM.

OOM is the abbreviation OutOfMemoryError, referring to memory overflow meaning.

Why not allow the use of Executors?

Let's look at a simple example:

ExecutorService maxFixedThreadPool =  Executors.newFixedThreadPool(10);
for (int i = 0; i < Integer.MAX_VALUE; i++) {
    maxFixedThreadPool.execute(()->{
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}

After setting the JVM (Java Virtual Machine) startup parameters: -Xmx10m -Xms10m(JVM set equal to the maximum operating memory 10M) to run the program, throws OOM exception information is as follows:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

at java.util.concurrent.LinkedBlockingQueue.offer(LinkedBlockingQueue.java:416)

at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1371)

at xxx.main(xxx.java:127)

Why would Executors of defective OOM?

By the above code, we found FixedThreadPool source code is as follows:

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

You can see LinkedBlockingQueue create FixedThreadPool used as a task queue, LinkedBlockingQueue continue to view the source code will find the root of the problem, the source code is as follows:

public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);
}

When using LinkedBlockingQueue did not give it a specified length, the default length of Integer.MAX_VALUE, which would cause the program to queue thread pool will add over multiple tasks, because the task is too big, there is the risk of OOM.

Related interview questions

1. The following program will output what result?

public static void main(String[] args) {
    ExecutorService workStealingPool = Executors.newWorkStealingPool();
    for (int i = 0; i < 5; i++) {
        int finalNumber = i;
        workStealingPool.execute(() -> {
            System.out.print(finalNumber);
        });
    }
}

A: No any output B: outputs 0-4 (containing 0,4) ordered digital C: outputs 0-4 (containing 0,4) random numbers of D: All of the above for

Answer: C

Topic resolve: newWorkStealingPool internal implementation is ForkJoinPool, it works by using a divide and conquer algorithm recursively dividing tasks into smaller sub-tasks, and then assign tasks to handle different threads execute concurrently.

2.Executors can create single-threaded thread pool it? How to create?

A: Executors can create a single-threaded thread pool, create divided into two ways:

  • Executors.newSingleThreadExecutor (): Creates a single-threaded thread pool.
  • Executors.newSingleThreadScheduledExecutor (): create a periodic task can perform single-threaded pool.

3.Executors in which thread for a short time to perform a number of tasks?

A: newCachedThreadPool () suitable for handling a large number of short-term tasks. It will try to thread the cache and reuse, if no cache task will create a new task, if the time limit of more than sixty seconds a thread, the thread pool will be removed, so it is more suitable for processing a large number of tasks in a short time.

4. You can perform periodic tasks which have a thread pool?

A: perform periodic task thread pool has two, namely: newScheduledThreadPool () and newSingleThreadScheduledExecutor (), which newSingleThreadScheduledExecutor () is newScheduledThreadPool () single-threaded version.

What 5.JDK 8 new thread pool? What are the characteristics?

A: JDK 8 new thread pool is newWorkStealingPool (n), if the number of concurrent not specified (i.e. not specified n), newWorkStealingPool () generates a corresponding number of thread pool based on the current number of CPU processor. It is characterized by the execution order of parallel processing tasks, the task is not guaranteed.

6.newFixedThreadPool and ThreadPoolExecutor What is the relationship?

A: newFixedThreadPool is ThreadPoolExecutor packaging, newFixedThreadPool bottom is achieved by ThreadPoolExecutor.

newFixedThreadPool realize source as follows:

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

7. What is the meaning of existence of single-threaded thread pool is?

A: The single-threaded thread pool provides queuing, if there are multiple task execution queue, can guarantee the order of the tasks performed. Single-threaded thread pool can reuse existing threads, reducing system performance overhead of creating and destroying threads.

8. Why is recommended to use the thread pool ThreadPoolExecutor create, rather than Executors?

A: Use ThreadPoolExecutor allow developers to more explicit operating rules thread pool, to avoid the risk of resource depletion.

Executors return to the thread pool disadvantage as follows:

  • FixedThreadPool and SingleThreadPool permission request queue length of Integer.MAX_VALUE, may accumulate a large number of requests may cause a memory overflow;
  • CachedThreadPool and ScheduledThreadPool number of threads to allow the creation of Integer.MAX_VALUE, to create a large number of threads, can cause memory overflow.

to sum up

Executors can create six different types of thread pool, which newFixedThreadPool () for a fixed number of tasks within the execution unit time, newCachedThreadPool () for a short time a large number of processing tasks, newSingleThreadExecutor () and newSingleThreadScheduledExecutor () is a single-threaded thread pool, and newSingleThreadScheduledExecutor () may be performing a periodic task is single-threaded version newScheduledThreadPool (n), while newWorkStealingPool () is a new JDK 8 concurrent thread pool, depending on the number of current generation computer CPU processing thread pool number comparison, but its implementation is concurrent execution order does not guarantee execution of the task.


I welcome the attention of the public number, keyword reply " the Java ", there will be a gift both hands! ! ! I wish you a successful interview ! ! !

% 97% E5% 8F% B7 % E4% BA% 8C% E7% BB% B4% E7% A0% 81.png)

Guess you like

Origin www.cnblogs.com/dailyprogrammer/p/12272748.html