011 Deep understanding of synchronized

I. Overview

Earlier we used synchronized to complete the implementation of an atomic method. Now we need to understand this keyword in depth.


 

2. How to use

  We use this keyword in four ways:

  [1] Modification of ordinary methods

  [2] Decorate static methods

  [3] Add a mutex to the instance object

  [4] Add mutex lock to class object

The first thing we need to know is that synchronized is the use of mutual exclusion locks to complete thread synchronization.

    The principle is to maintain mutual exclusion for operations on critical resources.


 

3. Implementation

public synchronized void add1() {
            count ++;
        }
        
        public static void add2() {
            count ++;
        }
        
        public void add3() {
            synchronized (this) {
                count ++ ;
            }
        }
        
        public static void  add4() {
            synchronized (Test.class) {
                count ++;
                
            }
        }

In the above code, we use the synchronized keyword in different places, and it seems that the situation is more complicated.

  But to summarize some:

    Synchronized is to complete the concept of mutual exclusion lock. The thread that has acquired the lock can run, and other threads that have not acquired the lock will enter if they cannot grab the lock.

      in the block queue.

  Then the :synchronized keyword to modify the instance method is equivalent to using the object currently calling the method as a mutex.

    The modified static method is equivalent to getting the class bytecode as a mutex.


 

4. Restrictions

  The limitation of the mutual exclusion lock represented by the synchronized keyword is relatively large,

    Once a thread fails to grab the lock, it will enter the blocking queue and need to wait for the lock to be released again.

      If the thread that preempts the lock is running for a long time, the cost of the mutex is too high.

        Therefore, JDK introduced biased locks and spin locks later to improve mutex locks. 

          But they are essentially mutex locks, so the mutex lock represented by this keyword is a heavyweight lock.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325149579&siteId=291194637
011