Synchronization (two) - Lock

lock:

Java is divided into types of locks: Lock bias, spin locks, lock lightweight, heavyweight lock

Locks use: first to provide biased locking, not satisfied when upgraded to lightweight lock time if they are not met, the expansion into a heavyweight lock. Spin lock is a transitional state, not an actual lock type. Lock can not upgrade downgrade.

Biased locking

  If there is a relationship when competition code will not, in order to allow the thread to get the price lower lock, which locks first use. (JVM compiled code, interpreted execution time, it will automatically give up the synchronization information, synchronization code to eliminate the results of synchronized)

  principle

When a thread to acquire the lock and access the sync block, will object header and a stack frame lock records stored in the lock bias thread ID, when the thread enters and exits after this sync block is not required to lock unlock CAS operation (sufficient to detect Mark Word is not stored inside the thread ID).

If the test succeeds, it said it had obtained a lock. If it fails, it is necessary to test whether the flag is biased locking 1, if it is 0, it attempts to lock contention by CAS; if it is 1, the CAS will attempt to use the object head to catch toward the current thread.

Biased locking only until competition time will release the lock. If other threads compete biased locking, will first suspend thread has biased locking and detection is active, no: the object header is set to lock-free state; is: the thread's stack will be executed, Mark Word or re-bias the other thread, no return to either lock or mark object to be unsuitable as an object lock.

  PS

Can be closed by a biased locking JVM parameters: - XX UseBiasedLocking = false, the default state directly into a lightweight lock.

Spinlocks

  It is a state, the current way of using spin thread attempts to obtain a lightweight lock.

Lightweight lock

  When biased locking is not satisfied, that is, concurrent access to multiple threads, locks the same object, it will be time to upgrade to a lightweight lock (also using the mark ACC_SYNCHRONIZED mark recorded record mark .ACC_UNSYNCHRONIZED not get the lock information the rout).

  principle

Before executing the synchronization code blocks, creates a lock space for storing in the stack frame is recorded, then copy the object header to Mark Word (referred displaced mark word) the lock record. The thread then try to use the CAS will replace Mark Word to point to lock the record pointer in the object header, success is to get a lock, and will continue to fail to get the spin.

When unlocked, the CAS will use atomic operations to replace the locks on the object head back, the lock is released, if the current lock failure indicates the presence of competition (other threads spin-count limit is reached, it will be expanded into a heavyweight lock lock), this time has been saved Mark Word heavyweight lock pointer, this time competing lock threads are blocked. Then release the lock, to re-awaken the blocked thread lock contention blocks access synchronization.

Heavyweight lock

  Heavyweight thread holds the lock to perform synchronization method of the resource, the rest of the thread is blocked. Mark Word points to monitor (mutex) the first address.

  principle

Each object has a monitor object corresponding thereto, when a monitor is held, and it is locked. Synchronization code block using monitorEnter instructions and monitorExit achieved. monitorEnter instructions after compilation will be inserted into the start position of the sync block, monitorExit the code will be inserted into the end position. Thread execution to enter the time will try to obtain ownership of the monitor.

monitor attributes:

_Owner mark the current thread of execution for the record. Initially to NULL. When a thread owns the monitor, owner tag that uniquely identifies that thread. When a thread releases the monitor, owner has returned to NULL. owner is a critical resource, JVM is by CAS operation to ensure its thread-safe.

_count record number of entries into the lock

_WaitSet is used to manage the queue (wait) thread,

_EntryList is used to manage the pool of lock blocking thread (_cxq queue eligible),

_cxq: competition in the queue, all requests lock the thread will first be placed in the queue (one-way links). _cxq is a critical resource, JVM to modify _cxq atomic instruction queue by CAS. _cxq is a LIFO stack (stack).

ACC_SYNCRHONIZED

When a JVM execution engine to execute a method that will get access_flags the method from the method area, check whether there ACC_SYNCRHONIZED identifier, the identifier if there is, then the current method is a synchronous method, you need to get the current object monitor, come to execute the method.

process

When multiple threads concurrently access the same synchronization code, will first enter _EntryList, when the thread gets the lock mark, monitor the _Owner record this thread, and execute monitor counter is incremented calculation (+1), on behalf of the lock, and continues to block other threads in _EntryList in. If the execution thread calls the wait method, the monitor assigned to perform the counter to zero calculations and _Owner mark assigned to null, give up on behalf of the lock, a thread of execution as _WaitSet into the obstruction. If the execution thread calls notify / notifyAll method, _WaitSet the thread wakes up, enter _EntryList in blocked waiting to acquire a lock mark. If the synchronization code execution thread of execution ends, it will also release the lock flag, _Owner the monitor tag assignment is null, and the counter values ​​0 calculation.

Other locks

ReentracntLock

Fair locks

  Fair locks record long wait, the longest waiting to execute. Queue.

 private Lock lock = new ReentrantLock(true);

Try to lock

  Try to use the lock, if you can not get the resources, it will not be blocked, and then execute other code.

  

lock.tryLock (); 
blocking attempts to lock, blocking some time to try to acquire a lock mark. 
lock.tryLock ( . 5, TimeUnit.SECONDS);

 

condition

  Condition, Lock increase for the condition. When the conditions are satisfied, do something, such as locking or unlocking. Such as waiting or wake.

 private Lock lock = new ReentrantLock();
 private Condition producer = lock.newCondition();
 private Condition consumer = lock.newCondition();

producer.await();
consumer.signalAll();

 

 

Guess you like

Origin www.cnblogs.com/RobertLionLin/p/11511570.html