Java_ use Method-level synchronized keywords

Source: Internet
Author: User

Why do you say so, because the author is this pit past (in fact, oneself pit oneself) ╮ (╯_╰) ╭

Let's look at some synchronized:

Synchronized is a keyword in the Java language that, when used to decorate a method or a block of code, guarantees that at most one thread executes the code at the same time.

First, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.

Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, other threads will block access to all other synchronized (this) synchronization blocks in object.

The third example also applies to other synchronous blocks of code. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.

The above rules apply to other object locks as well. To put it simply, synchronized is declaring a lock for the current thread, the thread that owns the lock can execute the instructions inside the block, and the other threads can only wait for the lock to get the same operation. This is very useful, but I encountered another kind of more wonderful situation. 1. In the same class, there are two methods using the Synchronized Keyword declaration 2. When one of the methods is executed, wait for another method (asynchronous thread callback) to execute, so a countdownlatch is used to wait 3. The code is deconstructed as follows:
synchronized void  A () {  countdownlatch = new Countdownlatch (1);  Do someing  countdownlatch.await ();} synchronized void B () {     countdownlatch.countdown ();}
Where a method is executed by the main thread, and the B method is executed by an asynchronous thread, the result of the callback execution is: The main thread executes the A method and starts to get stuck, no more, no matter how long you wait. This is a very classic deadlock problem a wait for B to execute, actually do not see B is the callback, B is also waiting for a to execute. Why is it? Synchronized played a role. In general, when we want to synchronized a block of code, we need to use a shared variable to lock it, such as:
Byte[]  Mutex = new Byte[0];void A1 () {     synchronized (mutex) {          //dosomething     }}void B1 () {     Synchronized (mutex) {          //dosomething     }}
  If the contents of the A method and the B method are migrated separately into the synchronized block of the A1 and B1 methods, it will be well understood.  A1 after execution will wait (Countdownlatch) B1 method execution   However due to A1 The mutex is not released, it begins to wait for B1, at this time, even if the asynchronous callback B1 method, because the need to wait for the mutex to release the lock, so the B method does not execute thus causing the deadlock   here the Synchronized keyword is placed in front of the method, The effect is the same. Just the Java language has helped you to hide the declaration and use of the mutex. The mutex used by the Synchronized method in the same object is the same, so even asynchronous callbacks can cause deadlocks, so be aware of this problem. This level of error is the Synchronized keyword used improperly. Don't mess with it, and use the invisible mutex object to .  so what exactly is it??  is easy to think of is the instance itself. Because then you don't have to define a new object and make a lock. To prove the idea, you can write a program to prove that the .  idea is simple, define a class, have two methods, a method declared as  synchronized, a method body that uses synchronized (this), and then start two threads, To call these two methods separately, if there is a lock contention (wait) between the two methods, it can be explained that the invisible mutex in the  synchronized of the method declaration is actually the instance itself . 
public class Multithreadsync {public synchronized void M1 () throws interruptedexception{System. Out.println ("         M1 call "); Thread.         Sleep (2000); System.    OUT.PRINTLN ("M1 Call done"); } public void M2 () throws interruptedexception{synchronized (this) {System. out.println ("M2 cal             L "); Thread.             Sleep (2000); System.         Out.println ("M2 call done");         }} public static void Main (string[] args) {final Multithreadsync thisobj = new Multithreadsync ();                      Thread t1 = new Thread () {@Override public void run () {try {                 THISOBJ.M1 ();                 } catch (Interruptedexception e) {e.printstacktrace ();         }             }         };                      Thread t2 = new Thread () {@Override public void run () {try {                 THISOBJ.M2 (); } CatCH (interruptedexception e) {e.printstacktrace ();         }             }         };         T1.start ();    T2.start (); }}
The result output is: M1 Callm1 call donem2 callm2 The Do description method m2 The sync block waits for the M1 to execute. This will confirm the above assumptions. It is also necessary to note that when sync is added to the static method, because it is a class-level method, the locked object is the class instance of the current classes. You can also write a program to prove it. Here is a little. So the synchronized keyword of the method can be automatically replaced with synchronized (this) {} when reading.
                                        void method () {void Synchronized method () {                 synchronized (this) {      //Biz Code                               //Biz Code}                             ------>> >      }                                        }

Java_ use Method-level synchronized keywords

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: info-contact@alibabacloud.com 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.