Notes on java synchronization (1)

Record some knowledge points of synchronization.

1. What are synchronized methods and synchronized code blocks?

Using the synchronized keyword, the difference in the level of detail of the code block! In fact, it is recommended to use BlockQueue, Executor, synchronized collections, etc. first, then the synchronized keyword, and finally Lock/Condition.

2. What is a monitor?

Built into every Object object, it ensures that only one thread can access specific data and code at a time.
Monitors and locks are used together in the Java Virtual Machine. A monitor monitors a block of synchronized code to ensure that only one thread executes the synchronized block at a time. Each monitor is associated with an object reference. A thread is not allowed to execute synchronized code until the lock is acquired.

3.Lock vs synchronized

Compared with synchronized, Lock's operation is more flexible, and Lock provides multiple ways to acquire locks, including Lock, ReadWriteLock interfaces, and ReentrantLock and ReentrantReadWriteLock classes that implement these two interfaces. The differences summarized by experts are as follows:

  1. Lock is an interface, and synchronized is a keyword in Java, and synchronized is a built-in language implementation;
  2. When an exception occurs, synchronized will automatically release the lock occupied by the thread, so it will not cause a deadlock phenomenon; and when an exception occurs, if Lock does not actively release the lock through unLock(), it is likely to cause a deadlock phenomenon, so When using Lock, you need to release the lock in the finally block;
  3. Lock can make the thread waiting for the lock respond to the interrupt, but synchronized does not. When using synchronized, the waiting thread will wait forever and cannot respond to the interrupt;
  4. Through Lock, you can know whether the lock has been successfully acquired, but synchronized cannot;
  5. Lock can improve the efficiency of reading operations by multiple threads.

In terms of performance, if the competing resources are not fierce, the performance of the two is similar, but when the competing resources are very fierce (that is, there are a large number of threads competing at the same time), the performance of Lock is far better than synchronized. Therefore, the specific use should be selected according to the appropriate situation.

4. How to specify the order of acquiring locks?

Reason: To avoid deadlock, for example, when bank transfer needs to lock the account, there may be deadlock (all waiting to obtain the lock of another account).
method:

=====================================
Questions? help? criticize? Comments welcome | QQ: 593159978
======================================

Guess you like

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