Re-recognize synchronized (top)

Source: Internet
Author: User

Synchronized was known as the heavyweight lock before JDK5, and was a rather chicken design, and in JDK6 the synchronized intrinsic mechanism was significantly optimized, adding CAs, lightweight locks and biased locking functions, Performance has been similar to Reentrantlock, and synchronized in the use of more simple, not easy to make mistakes (avoid the philosopher dining problem caused by deadlock), so if only to achieve mutual exclusion, and do not need to use lock-based additional properties (interrupts, conditions, etc.), It is recommended to use synchronized first.

Synchronized usage

Synchronized has a synchronous method and a synchronous statement block, which locks the object and scope two dimensions, and the mutex takes effect when the locked object enters the scope. when a thread accesses an object that has the same lock, it must be entered in a serial manner when it enters the scope . The modified objects are: decorated common methods (also known as synchronous methods), decorated static methods, decorated object instances, decorated class literals (class name literal constants).

Modifying a common method

Also known as the synchronous method, locking is called the synchronous method object. When a thread accesses a synchronized block of code in an instance object, other threads that attempt to access the synchronized-decorated area of the object are blocked. The same object shares a lock that can only have one synchronized zone at a time to obtain a lock, which can be called an object lock . There are two points to note: (1) The effect will only be on the same instance, (2) all the synchronized decorated areas of the object. For example: For Fooa objects, thread t1,t2 access MethodA is mutually exclusive, and thread T1,t2 access Methoda,methodb is also mutually exclusive; when MethodA is accessed, MethodB is not accessible and methodc can be accessed.

1  Public classFooImplementsRunnable {2      Public Static synchronized voidMethodA () {3         //TODO4     }5 6      Public Static synchronized voidMethodB () {7         //TODO8     }9 Ten      Public voidmethodc () { One         //TODO A     } -  -      Public Static voidMain (string[] args) { theFoo Fooa =NewFoo (); -Foo Foob =NewFoo (); -  -Thread T1 =NewThread (Fooa, "T1"); +Thread t2 =NewThread (Foob, "T2"); - T1.start (); + T2.start (); A     } at}

Modifying static methods

A lock is a class that a static method belongs to, at which point the class has a common lock, which can be called a class lock . When a thread accesses the synchronized static method, other threads that attempt to access the area of the class synchronized adornment will block, and not the synchronized-decorated area will not block. A modified static method is a variant that modifies the normal method, which locks the class (it does not matter with the object), which refers to locking the current object. For example, thread t1,t2 access to Methoda,methodb is also mutually exclusive.

Synchronous statement block

The case of a decorated object instance is consistent with the normal method of adornment, except that it is mutually exclusive when the thread enters the synchronous statement block. The Modified class literals (class name literal constant) is consistent with the decorated static method. For example: methodd locks the current object, while the synchronized in Methode locks all objects of the Foo class.

1  Public classFoo {2      Public voidmethodd () {3         synchronized( This) {4             //TODO5         }6     }7 8      Public voidMethode () {9         synchronized(Foo.)class) {Ten             //TODO One         } A     } -}

Synchronized mechanism

Synchronized is a way that Java provides for inter-thread communication, and this synchronization mechanism of synchronized is a mutex mechanism. The ways to implement mutexes are: Critical sections (Critical section), mutexes (mutexes), semaphores (semaphores), and Events (event).

Synchronized is a critical section of the way to achieve mutual exclusion, through the serialization of multithreading to access public resources or a piece of code, to ensure that only one thread at a time to access the critical area of shared data. If multiple threads attempt to access the critical section at the same time, after one of the threads has preempted the critical section, other threads that attempt to access the critical section will hang until the thread enters the critical section. For a chestnut, the meeting room resources are relatively tense, there are many teams need to use the conference room, then see which team quickly. When the team grabs to the conference room, it suspends the "in-session" cue, and other people who need to use the conference room see it waiting until the team that is currently using the conference room is finished, removing the "in session" cue.

The synchronized also guarantees visibility. After the mutex is released, ensure that one thread modifies the state of the object, which is visible to other threads, that is, the thread that subsequently acquires the lock guarantees the state of the most recent shared resource. The synchronized mutex is implemented through the monitor.

What is a monitor

A monitor is a synchronization mechanism. By acquiring and releasing locks, it is ensured that the shared resources can be mutually exclusive between threads, with at most one thread occupying the monitor at the same time, the mutex (mutex), and the conditional variable (Condition Variables). A method that allows a thread to block and wait for another thread to send a signal compensates for the lack of a mutex, which is the mutual exclusion and collaboration of the Monitor.

When multiple threads access a synchronized code at the same time, the newly requested line routines is first added to the entry set set, and through the competition (compete), only one thread can compete successfully and get the monitor to enter the Owner. The thread that gets the monitor calls wait () and then releases the monitor and wakes up into the wait set collection waiting for the condition to be met. Both acquire and release use atomic directives such as Test-and-set, compare-and-set to implement spin locks to ensure access to critical segments.

      1. Java Synchronized Keyword parsing
      2. The difference between a critical section, a mutex, a semaphore, an event
      3. Monitor (synchronization))
      4. Synchronized and object ' s Monitor

Re-recognize synchronized (top)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.