[JUC concurrent programming] Summary of JUC essential knowledge

JUC overview

What is JUC

JUC is the abbreviation of java.util.concurrent toolkit, which is a toolkit for processing threads. JDK1.5 began to appear

process thread

Process: refers to an application program running in the system, the process is the smallest unit of CPU resource allocation
Thread: the basic unit of processor time resources allocated by the system, a unit execution flow that is independently executed in the process. A thread is the smallest unit of program execution.

the state of the thread

  1. NEW New
  2. RUNNABLE is ready
  3. BLOCKED
  4. WAITING see you around
  5. TIMED_WAITING is out of date
  6. TERMINATED

The difference between wait and sleep

  1. sleep is a static method of Thread, and wait is a method of Object, which can be called by any instance object.
  2. sleep does not release the lock, nor does it need to hold the lock. wait will release the lock, but the premise of calling it is that the current thread holds the lock (the code is in synchronized)
  3. can be interrupted by the interrupted method.

Concurrency and Parallelism

Concurrency: At the same time, multiple threads access the same resource, and multiple threads are
parallel to a point [E-commerce spike]: Multiple jobs are executed together and then aggregated.

monitor

The monitor is the monitor monitor, that is, the lock, which is a synchronization mechanism to ensure that only one thread accesses the protected data or code at the same time.
JVM synchronization is based on entry and exit and is managed using monitor objects.

User threads and daemon threads

User thread: Usually custom thread, the main thread ends, the user thread runs, and the JVM is still alive
Daemon thread: For example, the garbage collection thread, only the daemon thread has no user thread, and the JVM ends

Lock interface

synchronized Implementation of ticket selling example
Lock's reentrant lock Implementation of ticket selling example
The difference between Lock and synchronized

Inter-thread communication

Multi-threaded programming steps: ① Create resource classes, ② Judgment, work, and notification ③ Create multi-threaded calls to resource class methods ④ Prevent false wake-up problems
Inter-thread communication: Two threads alternately complete plus one minus one example
Customized communication, three Thread AA prints 5 times, BB prints 10 times, CC prints 15 times, and loops for 10 rounds

Thread safety of collections

ArrayList unsafe solution: ①vector ②Collections.synchronizedList() ③CopyOnWriteArrayList
HashSet unsafe solution: CopyOnWriteArraySet
HashMap unsafe solution: ConcurrentHashMap

multithreaded lock

range of locks

Every object in Java can act as a lock. It is manifested in the following three forms:

  1. For ordinary synchronized methods, the lock is the current instance object this
  2. For static synchronized methods, the lock is the current class bytecode, the Class object
  3. For synchronized method blocks, the lock is the object configured in the synchronized brackets

Fair lock and unfair lock

unfair lock May cause other threads to starve. (Do not ask if there is anyone, just grab it directly), high efficiency
fair lock The sun is shining (ask if anyone is there, and there is a queue), the efficiency is relatively low

reentrant lock

synchronized() is an implicit reentrant lock, and Lock is an explicit reentrant lock.
Reentrant lock features: You can freely enter multiple layers of locks. After opening the outer lock, you can continue to open the inner lock.

deadlock

what is deadlock

Two or more processes wait for each other because of competition for resources. If there is no external interference, they can no longer execute

Cause of deadlock

  1. Insufficient system resources
  2. Process run advance order is inappropriate
  3. Improper resource allocation
    Handwritten deadlock example.

Check for deadlock

  1. jps -l get the process number of the running program
  2. The jstack process number can verify whether a deadlock occurs

Callable interface

The difference between the Runable interface and the Callable interface

  1. Whether there is a return value, Callable has a return value
  2. Whether an exception is thrown, if the result cannot be calculated, an exception will be thrown
  3. The implementation method names are different, the Runable interface is the run method, and the Callable interface is the call method

If you want to create a thread through the Callable interface, you must pass the implementation class FutureTask of the Runnable interface. The FutureTask construction can pass the Callable, and then new Thread, put it into the FutureTask

Principle of FutureTask

For example:
1. The teacher is thirsty and has no water to drink in class. It is not appropriate to go to buy water. The lecture thread continues. Just open another thread, let the monitor buy water, buy it back and put it there. When the teacher needs it, get() directly.
2. Three students, three computing tasks, I am the main thread and need to count the results of their calculations. Assuming that the second classmate has a lot of computation, I start the summary from the first classmate, to the second classmate, he has not yet After the calculation is done, I will open a separate thread for the second student to let him continue the calculation, and I will summarize the third student. When I have finished summarizing the third classmate, I will go back and wait for the second classmate to finish the calculation and sum up.

JUC's powerful auxiliary class

Decrement count CountDownLatch

The constructor of CountDownLatch, passing in an initial count. The await method is blocking and only passes when the count is 0. countDown() is not blocking, it will decrement the count by one
Example : After 6 students have left, the monitor will lock the door

CyclicBarrier

cyclicBarrier.await(); When the set value is not reached, the statement after await will not be executed, the thread will be blocked, and the set value will be +1 for each blocking. After reaching the set value, the runnable interface of the cyclicBarrier object will be executed. The thread executes cyclicBarrier.await(); follow-up tasks
Example : Collect seven dragon balls to summon the dragon

Semaphore

acquire() method, acquire a permit from this semaphore, the thread will block
release() until a permit is provided, release a permit and return it to the semaphore

Example : 6 cars parked in three parking spaces

ReentrantReadWriteLock Read-write lock

Pessimistic lock, optimistic lock

Pessimistic locks, which do not support concurrent operations, are locked for each operation.
Optimistic locking, supports concurrent operations, changes the version number after the operation, and rolls back if the version number is found to have changed when other thread operations are submitted.

table lock, row lock

Table lock: The entire table is locked
Row lock: Only one row is locked
Row lock may deadlock

Read-write lock

Read-write locks can deadlock

insert image description here

Read-write lock features

Concurrent reading, exclusive writing, deadlocking of read locks and write locks may occur.
A resource can be accessed by multiple read threads, or by one writer thread, but cannot exist at the same time. Read-write mutual exclusion, write-write mutual exclusion Exclusion, read and read sharing.
ps: Read-write lock is essentially a spin lock
Example: Read-write lock cache.

shortcoming:

  1. Cause lock starvation, keep reading, unable to write operations, such as taking the subway, 100 people get on the bus and 1 person gets off, and it is blocked all the time.
  2. When reading, no thread can write, when writing, its own thread can read, other threads can not read

Write locks can be downgraded to read locks, but read locks cannot be upgraded to write locks
. Downgrade methods: 1. Acquire write locks 2. Acquire read locks 3. Release write locks 4. Release read locks, the downgrade of write locks to read locks is completed in real time process.

BlockingQueue blocking queue

Commonly used:

  1. ArrayBlockingQueue (commonly used) : A bounded blocking queue consisting of an array structure
  2. LinkedBlockingQueue (commonly used) : A bounded blocking queue composed of a linked list, the default size is the largest integer value
    Common methods:
    The first group of methods throws an exception add(e) remove() element()
    The second group of methods returns the special value offer (e) poll() peek()
    The third group of methods blocks put(e) take()
    The fourth group blocks, the timeout gives up offer(e, time, unit) poll(time, unit)

ThreadPool thread pool

Overview and Architecture

Thread pool features:

  1. Resource consumption can be reduced, and the consumption caused by thread creation and destruction can be reduced by reusing created threads.
  2. Improve response speed: when tasks arrive, they can be executed immediately without waiting for thread creation
  3. Improve the manageability of threads: Threads are scarce resources, and unlimited creation will consume system resources and reduce system stability. Thread pool can be used for unified allocation, tuning and monitoring

Architecture – Executor framework implementation

insert image description here

How to use thread pool

  1. A pool of N threads : Executors.newFixedThreadPool(int)
  2. One pool and one thread : Executors.newSingleThreadExecutor()
  3. Scalable thread pool : Executors.newCachedThreadPool()

The bottom layer is used ThreadPoolExecutor

The meaning of the seven parameters of ThreadPoolExecutor

  1. int corePoolSize, the number of resident threads (cores)
  2. int maximumPoolSize maximum number of threads
  3. long keepAliveTime, thread survival time
  4. TimeUnit unit , time unit
  5. BlockingQueue workQueue , blocking queue
  6. ThreadFactory threadFactory, thread factory
  7. RejectedExecutionHandler handler, rejection policy

Thread underlying workflow

insert image description here
Threads are created only when the execute() method is executed. First, resident threads are created according to the requirements, then the requirements enter the blocking queue, and more threads are created for direct processing, and then the rejection policy is required to be executed.

Four rejection strategies

  1. AbortPolicy (default): Throws an exception directly, preventing the system from running normally
  2. CallerRunsPolicy: will not discard tasks or throw exceptions, but will roll back some tasks to the caller
  3. DiscardOldestPolicy: Discard the longest waiting task in the queue, then add the current task to the queue and try to submit the current task again
  4. DiscardPolicy: do nothing

Fork/Join branch merge

Fork: Split complex tasks
Join: Combine the results of split tasks
Example: 1+2+…+100 splits are calculated separately and then merged

CompletableFuture asynchronous callback

CompletableFuture.runAsync() Asynchronous callback without return value
CompletableFuture.supplyAsync() Asynchronous callback with return value

Guess you like

Origin blog.csdn.net/weixin_44179010/article/details/122246498