Emotionally intelligent people are able to read and take care of the emotions of everyone around them, and good writing should be accessible to everyone.

Nietzsche once said that man cannot understand what he has not experienced. So I will try to make technical articles as concrete as possible so that everyone can understand them, so before we begin, let’s start with two life stories.

A handsome picture of Nietzsche:

I always thought Nietzsche was a Chinese sage, roughly the same as Zhuangzi. Later, I realized that he was a foreigner. I was shocked.

Life Case 1

In the early years, when a certain treasure double “11” suddenly went viral, and countless men and women went crazy “chopping off their hands”, the most painful day was not the “chopping off” after eating “ash”, but the long and heart-wrenching days waiting for the delivery boy.

In order to ease each other’s “pain”, the delivery companies have become “clever” by preparing enough people and cars in advance to meet the oncoming orders before the shopping festival.

At this point, when we encounter various shopping festivals, we no longer have to stare at the phone every day waiting for the delivery boy.

Life Case 2

The small United States is a company HR, every year at the beginning of the year is the small United States the most headache day. Because a large number of employees quit at the beginning of the year, so Xiao Mei needs to deal with the procedures of leaving employees, while hiring people crazy, in addition to these jobs, Xiao Mei has to endure from various departments and BOSS intermittent urging, all these make Xiao Mei painful.

So in order to deal with this awkward situation at the beginning of each year, Mei also becomes smarter, she will recruit some employees at the end of each year, in case of the next year.

Since using this trick, Mei has lived happily ever after.

concept

Pooling refers to the preparation of resources in advance that can be reused as needed.

In other words, pooling has two advantages:

  1. Pre-created;
  2. Reuse.

Analysis of advantages of pooling technology

In the case of object creation in Java, the following steps are required for object creation:

  1. Finds a symbolic reference to the class in the constant pool based on the argument following the new identifier;
  2. If no symbol application is found (the class is not loaded), load, parse, initialize the class, etc.
  3. The VM allocates memory in the heap for the object, initializes the allocated memory to 0, and establishes the corresponding description structure for the object header (time-consuming operations: finding free areas in the heap, modifying the memory allocation status, etc.).
  4. Call the initialization method of the object (time-consuming operation: the user’s complex logical verification operations, such as IO, numerical calculation is in compliance with regulations, etc.).

As we can see from the above process, creating a class is a complex and time-consuming operation, so we should reuse existing classes as much as possible to ensure that the program runs efficiently, although it is better to create them in advance, which can be implemented using pooling techniques.

Pooling technology is commonly used

Common pooling techniques are used: thread pool, memory pool, database connection pool, HttpClient connection pool, and so on.

1. The thread pool

The principle of a thread pool is simple, similar to the concept of a buffer in an operating system. The thread pool starts with a number of threads, all of which are in a sleeping state. When a client has a new request, it wakes up one of the sleeping threads in the thread pool to process the client’s request. When it finishes processing the request, the thread goes back to sleep.

Thread pools can significantly improve performance. Such as a provincial data of county bank network center, the peak concurrent client requests per second more than 100, if you create a new thread for each client request, the amount of CPU time and memory is very breathtaking, if using a thread pool with 200 threads, it will save a lot of system resources, This allows more CPU time and memory to be used for real business applications, rather than frequent thread creation and destruction.

2. The memory pool

How to better manage your application’s memory usage, while increasing the frequency of memory usage, is a question worth pondering for every developer. Memory pools provide a more viable solution.

During the creation of a memory pool, a large enough memory is allocated in advance to form a preliminary memory pool. Each time the user requests memory, it returns a free chunk of memory in the pool and flags it as used. When the memory is used up, it is not the process of calling free or delete, but the process of storing the memory back to the pool, and the process of putting back to set the flag to free. At the end of the application, the memory pool is destroyed, freeing each chunk of memory in the pool.

Advantages of memory pools:

  • This advantage can be seen in the process of creating a memory pool. When we create a memory pool, we allocate regular chunks of memory, which reduces the generation of memory fragmentation.
  • Improved memory usage. This can be seen in the process of allocating and freeing memory. Each allocation and release does not call system-provided functions or operators to manipulate actual memory, but rather memory in the overused memory pool.

Disadvantages of memory pools: Memory is wasted because to use a memory pool, a large amount of free memory is allocated initially, which may not all be used.

3. Database connection pool

The basic idea of the database connection pool is to store the database connection as an object in memory when the system is initialized. When the user needs to access the database, instead of establishing a new connection, he will take an established free connection object from the connection pool. After use, the user does not close the connection, but puts it back into the connection pool for the next request to access, and these connections are established and disconnected by the connection pool itself.

In addition, you can set connection pool parameters to control the initial number of connections in the connection pool, the upper and lower limits of connections, the maximum number of connections used, and the maximum idle time of each connection. Of course, you can also monitor the number of connections, usage, and so on through the connection pool’s own management mechanism.

4. HttpClient connection pool

HttpClient is often used for HTTP service access. Our project will have a function to get the execution status of the task using HttpClient, once a second request, often with Conection Reset exception. The problem, it turns out, is that HttpClient creates a new connection with each request. When connections are created more often than connections are closed, a large number of connections in the TIME_CLOSED state are created in the system. Reuse connections using connection pools can solve this problem.

Actual: Threads VS thread pools

In this article, we use the previous article “6 methods of fast code execution time” to test the difference between thread and thread pool execution time. The test code is:

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

Thread pool vs thread performance comparison */
public class ThreadPoolPerformance {
	// The maximum number of executions
    public static final int maxCount = 1000;

    public static void main(String[] args) throws InterruptedException {
        // Thread test code
        ThreadPerformanceTest();

        // Thread pool test code
        ThreadPoolPerformanceTest();
    }

    Thread pool performance test */
    private static void ThreadPoolPerformanceTest(a) throws InterruptedException {
        // Start time
        long stime = System.currentTimeMillis();
        // Business code
        ThreadPoolExecutor tp = new ThreadPoolExecutor(10.10.0,
                TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        for (int i = 0; i < maxCount; i++) {
            tp.execute(new PerformanceRunnable());
        }
        tp.shutdown();
        tp.awaitTermination(1, TimeUnit.SECONDS);  // Wait for the thread pool to complete
        // End time
        long etime = System.currentTimeMillis();
        // Calculate the execution time
        System.out.printf("Thread pool execution duration: %d milliseconds.", (etime - stime));
        System.out.println();
    }

    /** thread performance test */
    private static void ThreadPerformanceTest(a) {
        // Start time
        long stime = System.currentTimeMillis();
        // Execute the business code
        for (int i = 0; i < maxCount; i++) {
            Thread td = new Thread(new PerformanceRunnable());
            td.start();
            try {
                td.join(); // Ensure that thread execution is complete
            } catch(InterruptedException e) { e.printStackTrace(); }}// End time
        long etime = System.currentTimeMillis();
        // Calculate the execution time
        System.out.printf("Thread execution duration: %d milliseconds.", (etime - stime));
        System.out.println();
    }

	// Business execution class
    static class PerformanceRunnable implements Runnable {
        @Override
        public void run(a) {
            for (int i = 0; i < maxCount; i++) {
                longnum = i * i + i; }}}}Copy the code

The execution result of the above program is as shown in the figure below:

conclusion

Based on our thread and thread pool tests, we saw a 10 times improvement in performance when we used the pooling technique. This test result does not represent the quantification of the performance of the pooling technology, as the test results are influenced by the method of execution and the number of cycles, but the significant performance difference is sufficient to illustrate the advantages of the pooling technology.

Similarly, Alibaba’s Java Development Manual also stipulates that “thread resources must be provided through thread pools, and it is not allowed to explicitly create threads in applications” as follows:

Reference & Quotation

zhuanlan.zhihu.com/p/32204303

www.cnblogs.com/yanggb/p/10…

Follow the official account “Java Chinese Community” for more exciting content.