Programming architecture (05): Java multithreading concurrency

Source code of this article: GitHub · click here | gitee · click here

1、 Multithreaded map

2、 Multithreading Foundation

1. Basic concepts

Thread is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operation unit in the process. A thread refers to a single sequential control flow in a process. Multiple threads can be concurrent in a process, and each thread executes different tasks in parallel.

2. Creation method

Inherit the thread class, implement the runnable interface, based on the callable and future interfaces, timer is the background thread and thread pool.

3. Thread state

Status description: initial status, running status, blocking status, waiting status, timeout waiting status and termination status.

4. Implementation mechanism

An application in the JVM can have multiple threads executing in parallel. The threads are mapped one-to-one to the operating system thread where the service is located, scheduled to execute on the available CPU, and an operating system thread will be created at startup; When the thread terminates, the operating system thread is also recycled.

5. Memory model

When the virtual machine starts running, multiple threads will be created. Some modules in the data area are shared by threads and some are thread private:

Thread sharing: metadata area and heap heap;

Thread private: virtual machine stack, local method stack and program counter;

A single CPU can only execute one thread at a specific time, so multiple threads use several pieces of space, and then constantly compete for the execution time of the CPU.

3、 Common concepts

1. Thread priority

The thread scheduler tends to execute threads with high thread priority. A high thread priority indicates a high probability of obtaining CPU resources, or the obtained execution time is fragmented, and the high probability of being executed does not mean that a thread with low priority must be executed finally.

2. Daemon thread

Daemon threads support auxiliary threads and mainly play a scheduling and supporting role in the program. When all non daemon threads in the JVM end, the daemon thread will also end.

3. Thread join

If thread a executes the join method of thread B, thread a will wait for thread B to finish executing and then return to continue executing.

4. Local thread

ThreadLocal, also known as thread local variable, creates a copy of the variable in each thread. Each thread can access its own internal copy variable, and threads do not affect each other.

4、 Thread safety

From the way threads and memory space are occupied in the above figure, it is necessary to ensure thread safety when threads access shared memory blocks.

1. Synchronous control

Synchronized keyword synchronization control can modify methods, code blocks, static methods, etc. synchronization control has less resources and can improve multithreading efficiency.

2. Locking mechanism

Lock interface: one of the root interfaces for resource locking in Java Concurrent Programming, which specifies several basic methods for resource locking.

Reentrantlock class: implements the reentrant lock of the lock interface, that is, if a thread obtains the lock of the current instance and enters the task method, it can enter the task method again when the thread does not release the lock. Characteristics: mutual exclusion and exclusivity, that is, only one thread enters the task at the same time.

Condition interface: describes condition variables that may be associated with locks, providing more powerful functions. For example, on the thread waiting / notification mechanism, condition can realize multi-channel notification and selective notification.

3. Volatile keyword

Volatile modifies a member variable, but not a method, that is, it identifies that the thread needs to obtain the variable from the shared memory when accessing the variable. The modification of the variable also needs to be synchronously refreshed to the shared memory to ensure the visibility of the variable to all threads.

5、 Thread communication

Thread is an independent individual, but in the process of thread execution, if the same business logic is processed, resource contention may occur, resulting in concurrency problems and even deadlock. Communication mechanism is needed to ensure the coordination between threads.

1. Basic method

The related method is the basic method of the object level in Java. Any object has this method: notify() randomly notifies a thread waiting on the object to end the wait state and return; The wait () thread enters the waiting state, does not scramble for lock objects, and can also set the waiting time;

2. Waiting / notification mechanism

Wait / notify mechanism. In this mode, thread a calls the object wait() method to enter the wait state when it does not meet the task execution. Thread B modifies the execution conditions of thread a and calls the object notify() or notifyall() method. Thread a returns from the wait state after receiving the notification, and then performs subsequent operations. The two threads complete the interaction between waiting and notification through wait () / notify () / notifyAll () and other methods provided by the object, so as to improve the scalability of the program.

3. Pipeline flow communication

Pipeline flow is mainly used to directly transfer data between different threads. One thread sends data to the output pipeline, and the other thread reads data from the input pipeline, so as to realize the communication between different threads.

6、 Thread pool

1. Executor interface

The executor system is designed to understand the coupling between thread task submission and task execution. The executor has various powerful implementation classes, which provide a convenient way to submit tasks and obtain task execution results. It encapsulates the process of task execution and no longer needs thread () Start() method, explicitly create a thread and associate execution tasks.

2. Core parameters

3. Related API classes

Thread pool task: core interfaces: runnable, callable interfaces and interface implementation classes;

Results of the task: interface future and implementation class futuretask;

Task execution: core interface executor and executorservice interface. In the executor framework, two core classes implement the executorservice interface, ThreadPoolExecutor and scheduledthreadpoolexecutor.

7、 Common thread API

1. Fork / join mechanism

Fork / join framework is used to execute tasks in parallel. The core idea is to divide a large task into multiple small tasks, and then summarize the execution results of each small task to get the final result of the large task. Core process: task segmentation, asynchronous execution of module tasks, and consolidation of single task results.

2. Container class

Concurrenthashmap: uses the segment lock mechanism to store the data in the container segment by segment, and then assigns a lock to each segment of data. When a thread accesses one segment of data using the lock, the data of other segments can also be accessed by other threads, that is, considering security and execution efficiency.

Concurrentlinkedqueue: Based on the unbounded thread safe queue of linked nodes, elements are sorted according to FIFO first in first out principle. The head of the queue is the element with the longest time in the queue, and the tail of the queue is the element with the shortest time in the queue. New elements are added to the tail of the queue, and the operation of obtaining elements is obtained from the head of the queue.

3. Atomic class

JDK has its own atomic operation class to handle the case that multiple threads operate a variable at the same time, including basic type, array type, reference type and attribute modification type.

8、 Application scenario

1. Timed task

By configuring and setting some programs to execute regularly at a specified time point or cycle time, the execution of tasks here is based on multithreading technology.

2. Asynchronous processing

Asynchronous processing is not executed according to the current synchronous code block program. Asynchronous processing is opposite to synchronous processing. Asynchronous implementation also requires multi threads or multi processes to improve program efficiency.

3. Task decomposition

It is a common operation in distributed databases. The data is distributed in replicas of different databases. When executing queries, each service has to run query tasks. Finally, data consolidation is performed on one service, or an intermediate engine layer is provided to summarize data. In large-scale timed tasks, the tasks to be processed are often divided according to specific policies, Multiple threads process at the same time.

4. Connection pool technology

The technology of creating and managing a connection buffer pool. These connections are ready to be used by any thread that needs them, so as to reduce the problem of continuous creation and release of connections and improve program efficiency.

9、 Source code address

GitHub·地址
https://github.com/cicadasmile
GitEE·地址
https://gitee.com/cicadasmile

Recommended reading: programming system sorting

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>