Synchronization lock: synchronized

1. The characteristics of synchronized

  1. Atomicity: The so-called atomicity refers to an operation or multiple operations, either all of them are executed and the execution process will not be interrupted by any factors, or they are not executed at all.
  2. Visibility: Visibility means that when multiple threads access a resource, the status, value information, etc. of the resource are visible to other threads.
  3. Orderliness: Orderliness refers to the order in which the program is executed in accordance with the code.

2. The use of synchronized

There are three main usages of Synchronized:

  1. Modified instance method: Acts on the current object instance to lock, and obtains the lock of the current object instance before entering the synchronization code.
  2. Modified static method: that is, to lock the current class, which will act on all object instances of the class. Before entering the synchronization code, the lock of the current class must be obtained. Because the static member does not belong to any instance object, it is a class member (static indicates that this is A static resource of this class, no matter how many objects are new, there is only one copy). Therefore, if a thread A calls a non-static synchronized method of an instance object, and thread B needs to call a static synchronized method of the class to which the instance object belongs, it is allowed, and mutual exclusion will not occur, because accessing the lock occupied by the static synchronized method It is the lock of the current class, and the lock occupied by accessing the non-static synchronized method is the current instance object lock.
  3. Modified code block: Specify the lock object and lock the given object/class. synchronized(this|object) means to acquire a lock on the given object before entering the synchronized codebase. synchronized(class.class) means to obtain the lock of the current class before entering the synchronization code.

Summary:
The synchronized keyword is added to the static static method and synchronized (class) code block to lock the Class class.
The synchronized keyword is added to the instance method to lock the object instance.

3. Synchronized lock mechanism

When a method or a piece of code block is modified by synchronized, it will not call the method immediately to lock, but first enter the biased lock from the lock-free state, and will not lock when there is no lock conflict, which can reduce some loading. The overhead of lock unlocking, when a lock conflict occurs, it will be locked immediately to become a lightweight lock, and when the lock conflict becomes more severe, it will be transformed into a heavyweight lock.
insert image description here

Guess you like

Origin blog.csdn.net/m0_71645055/article/details/132030053