The concept of locks in java

Spin locks (optimistic locking belongs)

In order not to give up the cpu execute the event, the use of recycling technology cas (when changing the value to again get to see whether the value of the value obtained with just the same, the same description is not to be changed by other threads, no action is performed while loop until the same date and then manipulate the values) attempt to update the data until it succeeds.

Pessimistic locking

Assume concurrency conflicts occur, synchronize all related operations on the data, the data is read from the start locked.

Optimistic locking

Assuming no conflict, when data is modified, if you find and retrieve data before is not the same, the latest data is read, modify and try again

Exclusive lock (write)

Add resources to write lock, the thread can modify resources, other threads can not be locked; (Write Once)

Shared lock (read)

After adding resources to read lock can only be read but not changed, other threads can only add a read lock, write lock can not be added; (read more)

Reentrant lock

After the thread got a lock, free access to the same lock the other code synchronization, such as a method of synchronized block call this method again, re-enter the synchronized block, lock, too, with a thread lock acquired after lock, can be obtained again and lock is provided with a number of methods to acquire the lock, simultaneously released, the corresponding number will be loosed, multiple calls to unlock

Non-reentrant lock

And opposite lock reentrant

Fair locks

The order of competition for the lock, if you press first come first served, for the fair

Unfair lock

In contrast with the fair locks

Relevant knowledge about the synchronization of the synchronized keyword

Synchronized keyword optimized content:
biased locking (no reduction in competition, JVM resource consumption)
there are two or more threads for -> lightweight lock (CAS modified state)
thread CAS after a certain number of spins, in order to avoid excessive multi-spin impact performance -> heavyweight lock (
Mark internal word address object will save a lock of a monitor, and a monitor object for each object, use the lock when the heavyweight objects on a monitor works a)

Object mark word which contains the four states Tag (. 11 00 01 10)
01 without lock
00 locks lightweight
10 wt lock
11 GC waste

Here Insert Picture Description

Published 43 original articles · won praise 12 · views 4667

Guess you like

Origin blog.csdn.net/Jarbein/article/details/102542458