Locks available in Java Multi-threading:synchronized and lock.
(a)synchronized
1,the use of synchronized
Each object is self-locking, the lock can synchronize the instance method (this is the object lock), the static method (class is the object lock), the method block (the synchronized parameter is the object lock )
Here's how to lock the instance:
Public synchronized void Add () { a++; }
Use note points:
(1) The Wait, notify, and Notifyall of object need to be locked in the outer layer of the code, wait and wake locks must be the same, the lock used cannot be changed, or the illegalmonitorstateexception exception will be thrown
/** * Thread waits for wake-up Test * * @author Peter_wang * @create-time 2014-10-9 pm 2:50:36 */public class Threadnotifytest {private STA Tic integer num = new Integer (0); /** * @param args */public static void main (string[] args) {final thread thead1 = new Thread () { @Override public void Run () {synchronized (num) {try { Sleep (2000); Num.wait (); System.out.println ("unlocked successfully"); } catch (Interruptedexception e) {e.printstacktrace (); } } } }; Thead1.start (); Thread thead2 = new Thread () {@Override public void run () {try { Sleep (+);//num = new Integer (1); A num++;//b} catch (Interruptedexception e) {E.PRintstacktrace (); } } }; Thead2.start (); }}Regardless of whether a or B is executed, when the lock num is changed, wait execution throwsillegalmonitorstateexceptionexception.
The wait, notify locking are to ensure that they are atomic in execution.
(2) The lock used as far as possible is an immutable object, using the private final object object, the changeable object can cause unpredictable consequences, such as a wait problem.
(3)synchronized lock area to minimize and improve performance.
2,synchronized principle Research
(1) Thread status
When multiple threads request an object monitor at the same time, object monitor sets several states to differentiate the requested thread:
Contention List: All threads that request a lock will be placed first in the competition queue
Entry list:contention List The threads that qualify as candidates are moved to the Entry list, reducing contention for the contention list
Wait set: Those threads that call the wait method to be blocked are placed into the wait set
OnDeck: There can be at most one line is impersonating at a competitive lock at any moment, the thread called OnDeck owner: the thread that gets the lock is called owner! Owner: The thread that freed the lock
(2) Lock type
Fair lock and non-fair lock
Fair Lock: Every thread has the same chance of getting a schedule.
Unfair lock: Each thread gets a different scheduling chance, 5-10 times the fair lock throughput rate
Spin Lock and Block lock
Spin Lock: Thread blocking scheduling process design to operate the Linux kernel thread, need to switch state between user state and kernel State, performance consumption is large, spin mechanism let the request scheduling thread internal self-loop, do not switch state wait for a period of time, if still failed to get the scheduling opportunity to convert the lock type
Blocking lock: When a blocking lock thread competes, no fetch to the scheduled threads directly into the blocking queue
Multiple blocking lock types
Biased lock: In most cases, the lock exists in a single thread, in order for the thread to obtain a lock to reduce the performance cost, the same thread multiple times, will not perform CAS operations until the multi-threaded competition, converted to other types
Light-weight Lock: Pro-lock version of the upgrade or directly set up the system does not use a biased lock directly into the light-weight lock, more than the preference of the lock step CAS operation, the current if the lock is not locked by other threads can be used, the operation failed to enter the spin lock
Weight Lock: Full blocking lock status, Object Monitor (monitoring), upgraded by spin lock timeout
The evolution of Locks: lock-on, light-weight, spin-lock, Weight lock
(3) Summary
Synchronized execution, priority to use a biased lock or light lock to improve performance, encountered multi-threaded lock phenomenon, into the spin state, waiting for the failure to enter the weight lock phase, blocking the thread, put in the blocking queue, switch thread state.
(ii) Lock
1, the use of Reentrantlock
Private Reentrantlock Mlock = new Reentrantlock (), @Override public Void Write () { mlock.lock (); try { long startTime = System.currenttimemillis (); System.out.println ("Start writing data to this buff ..."); for (;;) Impersonation to be processed for a long time { if (System.currenttimemillis ()-startTime > Integer.max_value) break ; } System.out.println ("finally finished"); } finally { mlock.unlock (); } }
Reentrantlock locks the instance object at lock, it must be unlock unlocked in Finally, preventing the exception from being thrown unlocked.
2.Reentrantlock Principle Analysis
The operations in Reentrantlock are inherited from Abstractqueuedsynchronizer based on Sync,sync .
Abstractqueuedsynchronizer accommodates all blocking threads by constructing a blocking-based CLH queue, and operations on that queue are through Lock-free (CAS) operations, but for the thread that has acquired the lock, The Reentrantlock implements the function of biased locking.
(iii) comparisonof synchronized and Reentrantlock
1, performance on synchronized is native method performance optimization,Reentrantlock is Java Layer Implementation performance is not necessarily very good.
2. Reentrantlock provides more features, such as fair lock and unfair lock settings, but requires the use of finally unlock.
3, in the ordinary case use synchronized, in the business complex need to use Reentrantlock special functions to use reentrantlock.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
java-Multi-threaded deep (vi) lock