Thread synchronization technology summary


Note: sort out some synchronization technologies for future review. At present, the technology is still learning, and the new knowledge of synchronization will be added to this article.

Single machine multithreading:

  • synchronized
    1. Interpretation:

    (1) JVM level synchronization technology, bytecode implementation. When there is a problem in code execution (such as throwing an exception), the JVM will automatically release the lock and let other blocked threads continue to execute
       (2) Reentrant: when the thread has acquired the lock object and enters the synchronization block again, the lock counter is + 1. When monitorexit is executed, the lock counter is - 1. When the counter is 0, the object is released

    2. Usage:

    (1) The instance object is used as a lock object: there may be multiple object instances. Therefore, if a single instance of the object cannot be guaranteed, synchronization may occur.
       (2) Class object as lock object: each class has only 1 class object.
       (3) Static * * synchronization method: use the instance object as the lock
       (4) Member synchronization method: use class object as lock

    3. Precautions:

    (1) Minimize the scope of synchronization, improve program concurrency and reduce the possibility of deadlock
       (2) Use the difference between class objects and instance objects
       (3) The difference between static methods and non static methods for synchronization
  • Lock interface
    1. Interpretation:

    (1) The synchronization of lock interface is more flexible and more complex to use
       (2) You can set the waiting time. When a thread requests a lock, if the waiting time exceeds, the thread stops waiting.
       (4) Lock can respond to interrupts and stop waiting threads.
       (5) The API provides a return value to know whether the thread successfully obtains the lock
       (6) Common implementation class: reentrantlock

    2. Usage: the thread needs to support interrupt and check whether the thread successfully obtains the lock
    3. Precautions:

    (1) The lock mechanism implemented at the code level. In case of exception, the JVM will not automatically release the lock. When using lock(), you must use unlokc()
  • ReentrantLock
    1. Interpretation:

    (1) The lock interface is implemented using AQS framework
       (2) Exclusive lock, only one thread can obtain and use resources
       (3) The construction method provides an optional fair parameter. What is the difference between fair and unfair? The so-called fair is to obtain locks in strict accordance with the order of FIFO. Non fair locks are obtained according to the programmer's own design rules. For example, they can be selected according to priority, run times and other rules

    (4) Multiple condition objects can be bound (condition objects mean that after a thread obtains a lock and enters the synchronization block, the condition of the condition object needs to be met, otherwise it will still hang and wait until other threads wake up)

  • CountDownLatch
    1. Interpretation:

    (1) Implemented using AQS framework
       (2) Shared lock, which can be held by multiple threads at the same time
       (3) The task is divided into n tasks, and the state field is initialized to n. Starting to execute the task, the calling thread calls the await() function and hangs. After each sub thread is executed, execute the countdown() function, and the state field is reduced by 1 until the field becomes 0. The calling thread returns from the countdown() function to continue subsequent actions.

    2. Usage:
    3. Precautions:

  • wait()、Notify()
    1. Interpretation:

    (1) Calling the wait () method of an object will suspend the thread holding the object until another thread calls the notify () method of the object
  • join()
    1. Interpretation:

    (1) calling the A thread's Join method in the B thread, B will wait for the A thread to finish and go down again.
  • CAS algorithm
    1. Interpretation:

    (1) An implementation of optimistic lock using retry

    2. Usage scenario:

  • Semaphore
    1. Interpretation:

    (1) It is realized by AQS.
       (2) Shared lock, which can be held by multiple threads at the same time
       (3) Internally maintain a "permission set", which is actually the state field, indicating that at most state threads can acquire locks at the same time (successfully call the acquire() function)
  • CyclicBarrier
    1. Interpretation:

    (1) Memory barrier. Set a goal. When all threads reach this goal, the program can execute down.
  • volatile
    1. Interpretation:

    (1) Variables decorated with volatile have visibility to all threads. One thread modifies the value of this variable, and other threads can know the new value immediately. The reasons are as follows: for shared variables, when one thread modifies the variable, other threads can only read the variable from the main memory, not from the working memory, so as to ensure that the variables read by the thread are up-to-date
       (2) The variable modified by volatile prohibits the optimization of instruction reordering (ordinary variables cannot guarantee that the order of variable assignment operation is the same as that in the code. Due to the optimization of instruction reordering, the code execution order may change after java code becomes assembly code)
       (3) Volatile cannot guarantee atomicity.
       (4) In addition to the volatile keyword, there are two other keywords that can also achieve visibility.
           A. Synchronize: "synchronize the values in the working memory to the main memory before unlocking the variable", and this rule obtains the visibility.
           B. Final: once the final modified field is initialized, the value of the final field can be seen in other threads

    2. Usage:

    (1) In some cases, locking can be avoided and program concurrency can be improved
  • ThreadLocal:
    1. ThreadLocal is used to realize data independence between threads, so as to avoid data sharing. Since the data is not shared, thread safety problems are naturally avoided. It is an optimization scheme for synchronization.

Cluster (multi process, multi thread)

  • Redis implements distributed locks
    1. Interpretation:

    (1) Redis is a single thread model, and a single command operation is atomic.
     (2) Nx instruction:
         a. Nx means that if the key does not exist, it will be added. If it exists, it will be returned directly
         b. Nx is the key to realize distributed locking.
         c. Example: set key UUID NX PX timeout
                 SET resource_name uniqueVal NX PX 30000

    2. Note:
    (1) In order to prevent the lock from being released due to various reasons, theexpire key secondSet the key to an expiration time
    (2) There may still be a problem with using expire to set the expiration time. For example, insetnx key valueandexpire key secondBetween, a system failure (or other reasons) occurs, which causes the key not to set the expiration time, or a deadlock may occur. At this time, an instruction can be usedset lock:codehole true ex 5 nx, this instruction is equivalent to executing setnx first and then expire, while ensuring atomicity.
    (3) When adding and releasing a lock, it is necessary to ensure that it is the same lock. The usual method is to use UUID and store it in the key. When releasing a lock, compare the values in UUID and key. If it is the same, it is the same lock.
    Why do you need to guarantee the same lock? Suppose there are three machines a, B and C. A obtains the lock first. Suppose a’s business execution time is relatively long and the lock expires (A’s lock is deleted). This is B’s request and acquisition of the lock. If a completes the execution at this time, a deletes B’s lock without judging whether it is the same lock. At this time, if C requests to obtain the lock again, B and C execute the business code at the same time.

  • Zookeeper implements distributed lock
    1. Reference:…