This is a mind map about Java concurrency. The main content includes: locks, thread pools, concurrent containers, and basic concepts.
Edited at 2024-04-22 19:41:17"九品小吏絕地逆襲!大唐'荔枝使'李善德被迫接下五千里的生死速遞貴妃生辰前,嶺南鮮荔枝必須抵達長安!面對同僚陷害、時限催命,他聯合胡商會長阿彌塔、臥底侍郎鄭平安,在左相暗線雲清與波斯商人蘇諒的助力下,以精密路線與冰鎮秘術搏一線生機。'退無可退,便向死而生!'這場跨越山海的味道爭奪戰,背後竟藏著右相貪污的驚天秘密……"一張圖給你解釋清楚,李善德和其他角色之間的關係。
"The ninth-rank minor official counterattacks! Li Shande, the Tang Dynasty 'litchi envoy's', was forced to take over the life and death express of 5,000 miles. Before the birth of the imperial concubine, Lingnan fresh litchi must arrive in Chang'an! Faced with the frame-up of his colleagues and the death limit of the time limit, he joined forces with the President of Hu Chamber of Commerce Amita and the Undercover Minister Zheng Ping'an, with the help of the left prime minister's secret line Yunqing and Persian businessman Su Liang, he used a precise route and ice secret technique to fight for a glimmer of hope. 'There is no way to retreat, and he will live to death!' This battle for the taste of the mountains and seas is hidden behind the shocking secrets of the right prime minister's corruption..." A picture explains to you clearly the relationship between Li Shande and other characters.
"Les contre-attaques officielles mineures du neuvième rang! Li Shande, la dynastie Tang 'Litchi Envoy's', a été forcée de reprendre la vie et la mort de 5 000 miles. Avant la naissance de la concubine impériale, Lingnan Fresh Litchi doit arriver à Chang'an! Le ministre infiltré Zheng Ping'an, avec l'aide de la ligne secrète du Premier ministre gauche Yunqing et de l'homme d'affaires persan Su Liang, il a utilisé une route précise et une technique secrète de glace pour lutter pour une lueur d'espoir. Cette bataille pour le goût des montagnes et des mers est cachée derrière les secrets choquants de la corruption du Premier ministre droit ... "Une image vous explique clairement la relation entre Li Shande et d'autres personnages.
"九品小吏絕地逆襲!大唐'荔枝使'李善德被迫接下五千里的生死速遞貴妃生辰前,嶺南鮮荔枝必須抵達長安!面對同僚陷害、時限催命,他聯合胡商會長阿彌塔、臥底侍郎鄭平安,在左相暗線雲清與波斯商人蘇諒的助力下,以精密路線與冰鎮秘術搏一線生機。'退無可退,便向死而生!'這場跨越山海的味道爭奪戰,背後竟藏著右相貪污的驚天秘密……"一張圖給你解釋清楚,李善德和其他角色之間的關係。
"The ninth-rank minor official counterattacks! Li Shande, the Tang Dynasty 'litchi envoy's', was forced to take over the life and death express of 5,000 miles. Before the birth of the imperial concubine, Lingnan fresh litchi must arrive in Chang'an! Faced with the frame-up of his colleagues and the death limit of the time limit, he joined forces with the President of Hu Chamber of Commerce Amita and the Undercover Minister Zheng Ping'an, with the help of the left prime minister's secret line Yunqing and Persian businessman Su Liang, he used a precise route and ice secret technique to fight for a glimmer of hope. 'There is no way to retreat, and he will live to death!' This battle for the taste of the mountains and seas is hidden behind the shocking secrets of the right prime minister's corruption..." A picture explains to you clearly the relationship between Li Shande and other characters.
"Les contre-attaques officielles mineures du neuvième rang! Li Shande, la dynastie Tang 'Litchi Envoy's', a été forcée de reprendre la vie et la mort de 5 000 miles. Avant la naissance de la concubine impériale, Lingnan Fresh Litchi doit arriver à Chang'an! Le ministre infiltré Zheng Ping'an, avec l'aide de la ligne secrète du Premier ministre gauche Yunqing et de l'homme d'affaires persan Su Liang, il a utilisé une route précise et une technique secrète de glace pour lutter pour une lueur d'espoir. Cette bataille pour le goût des montagnes et des mers est cachée derrière les secrets choquants de la corruption du Premier ministre droit ... "Une image vous explique clairement la relation entre Li Shande et d'autres personnages.
Java concurrency
basic concept
process
heap
method area
The heap and method area are resources shared by all threads. The heap is the largest piece of memory in the process and is mainly used to store newly created objects (almost all objects allocate memory here). The method area is mainly used to store loaded objects. Class information, constants, static variables, code compiled by just-in-time compiler and other data.
thread
program counter
Virtual machine stack
native method stack
There can be multiple threads in a process, and multiple threads share the heap and method area (metaspace after JDK1.8) resources of the process, but each thread has its own program counter, virtual machine stack and local method stack.
concurrent
parallel
Can easily lead to memory leaks, deadlocks, and thread insecurity
Synchronize
asynchronous
Thread safety
Create thread
Thread life cycle and status
NEW
Ready (Runnable)
Running
Blocked
Synchronous blocking (Blocked)
Waiting for blocking (WAITING)
Timeout waiting blocking (TMME-WAITING)
Death (Dead/TERMINATED)
Thread context switching
thread deadlock
Four necessary conditions for deadlock
How to prevent deadlock
How to troubleshoot
Graphical: jconsole
jps -l finds out the program process number, jstack process number
JMM
definition
background
CPU and cache coherence
Processor optimization
Parallel reordering of instructions
Compiler optimization rearrangement
Memory system rearrangement
Concurrency theory
as-if-serial rules
happens-before rule
program sequence rules
Monitor lock rules
Volatile variable rules
transitivity rule
start() rule
join() rules
Three major characteristics
atomicity
visibility
Orderliness
How to solve concurrency issues
Three major keywords
volatile
visibility
happens before principle
principle
write memory semantics
Read memory semantics
Orderliness
Implementation of memory semantics
synchronized
effect
atomicity
Orderliness
visibility
write memory semantics
Read memory semantics
Usage
Decorate instance methods
Modify static methods
Decorate code blocks
principle
synchronized code block
sync method
java object model
Object header
Mark Word
Klass Point
Instance data
Byte alignment
lock upgrade
no lock
Lock status
bias lock
Lock status
Upgrade time
Specific operations
benefit
The biased thread ID is inconsistent with the current thread ID.
Competition success
Competition failed
Technical realization
lightweight lock
Lock status
Upgrade time
effect
Spin
The difference between bias lock and bias lock
Heavyweight lock
Lock status
Upgrade time
principle
jdk1.6 optimization
spin lock
adaptive spin lock
lock elimination
lock roughening
bias lock
lightweight lock
final
effect
Reordering rules
Write reordering rules for final fields
Reordering rules for reading final fields
memory barrier
concurrent container
List
CopyOnWriteArrayList
Vector
Set
CopyOnWriteArraySet
Map
ConcurrentHashMap
ConcurrentSkipListMap
HashTable
queue
ArrayBlockingQueue
LinkedBlockingQueue
PriorityBlockingQueue
SynchronousQueue
Thread Pool
definition
Advantage
Reduce resource consumption
Improve response speed
Improve thread manageability
How to create
Executors
FixedThreadPool
SingleThreadExecutor
An unbounded LinkedBlockingQueue is probably used. The maximum length of the task queue is Integer.MAX_VALUE. A large number of requests may accumulate, resulting in OOM.
CachedThreadPool
The synchronization queue SynchronousQueue is used, and the number of threads allowed to be created is Integer.MAX_VALUE.
ScheduledThreadPool
The unbounded delayed blocking queue DelayedWorkQueue is used. The maximum length of the task queue is Integer.MAX_VALUE, which may accumulate a large number of requests, resulting in OOM.
ThreadPoolExecutor
Common parameters
corePoolSize
maximumPoolSize
workQueue
keepAliveTime
unit
threadFactory
handler
AbortPolicy
CallerRunsPolicy
DiscardPolicy
DiscardOldestPolicy
Process of handling tasks
How to set the size of the thread pool
Theoretical algorithm
empirical method
CPU intensive tasks (N 1)
I/O intensive tasks (2N)
Future class
Cancel task
Determine whether the task has been canceled
Determine whether the task has been completed
Get task execution results
shortcoming
CompletableFuture
Solve the shortcomings of Future
advantage
CompletionStage
Lock
basic concept
pessimistic lock
advantage
The cost of pessimistic locking is fixed
shortcoming
Fierce lock competition can cause thread blocking
A large number of blocked threads will cause context switching of the system Increase system performance overhead
Pessimistic locking may also cause deadlock problems
Applicable scene
Write multiple scenarios and fierce competition (to avoid frequent failures and retries that affect performance)
optimistic locking
advantage
There is no lock competition causing thread blocking
There will be no deadlock problem
shortcoming
If conflicts occur frequently (a lot of writes occur), there will be frequent failures and retries.
Applicable scene
Multiple reading scenarios, less competition (can avoid frequent locking affecting performance)
Implementation plan
Version number mechanism
CAS algorithm
ABA questions
Long cycle time and high overhead
Only atomic operations on a shared variable are guaranteed
ThreadLocal
effect
principle
Hash algorithm
Hash conflict
Memory leak problem
reason
solution
AQS
main idea
state
CLH queue
structure
principle
advantage
Excellent performance, low overhead for acquiring and releasing locks.
fair lock
Simple to implement and easy to understand
Strong scalability
shortcoming
Spin operation will cause large CPU overhead when the lock is held for a long time.
Single function and cannot support complex functions
CLH cohort variants
AQS changes spin operation to blocking thread operation
Improvements to lock data structures
Extend the state of each node
SIGNAL
PROPAGATE
CONDITION
CANCELLED
Explicitly maintain predecessor and successor nodes
Optimization of auxiliary GC such as explicitly setting the dequeue node to null
Schematic diagram
shared lock
exclusive lock
ReentrantLock
what is
principle
Unfair locking process
When thread one is locked successfully
AQS internal data
Thread two lock failed
CLH queue situation
Thread three lock failed
Fair lock locking process
Unlocking process
The process of releasing the lock
Waiting for queue data
final queue data
Condition
Implementation principle
ReentrantReadWriteLock
Applicable scene
Can a thread still acquire a write lock if it holds a read lock?
Read lock cannot be upgraded to write lock
Semaphore
Two modes
fair mode
Unfair model
principle
CountDownLatch
effect
principle
Disposable
CyclicBarrier
Atomic class
basic type
AtomicInteger
AtomicLong
AtomicBoolean
array type
AtomicIntegerArray
AtomicLongArray
AtomicReferenceArray
reference type
AtomicReference
AtomicStampedReference
Object property modification type
AtomicIntegerFieldUpdater
AtomicLongFieldUpdater
AtomicReferenceFieldUpdater