Home Java JavaBase What is the difference between synchronized and Lock?

What is the difference between synchronized and Lock?

Nov 19, 2020 am 11:38 AM
java lock synchronized

Difference: 1. Lock is an interface, and synchronized is a keyword of java. 2. Synchronized will automatically release the lock it holds when an exception occurs, so deadlock will not occur; when an exception occurs, synchronized will not actively release the lock it holds, and the lock must be released manually, which may cause deadlock.

What is the difference between synchronized and Lock?

#In distributed development, locks are an important way to control threads. Java also provides two lock mechanisms for this purpose, synchronized and lock.

0. Synchronized implementation principle

Every object in Java can be used as a lock, which is the basis for synchronized to achieve synchronization:

  • Ordinary synchronization method, the lock is the current instance object

  • Static synchronization method, the lock is the class object of the current class

  • Synchronization method block , the lock is the object in the brackets
    When a thread accesses a synchronized code block, it first needs to obtain the lock. When it exits or throws an exception, it must release the lock. So how does it implement this mechanism? Let’s look at a simple piece of code first:

package cn.alibab.javap;public class SynchronizedTest {

    public synchronized void test1(){

    }    public void test2(){        synchronized (this){

        }
    }
}
Copy after login

Use the javap tool (javap is a decomposer of class files after java compilation) to view the generated class file information to analyze the implementation of Synchronized

What is the difference between synchronized and Lock?

What is the difference between synchronized and Lock?
As can be seen from the above, the synchronization code block is implemented using the monitorenter and monitorexit instructions. The synchronization method (not visible here needs to look at the underlying implementation of the JVM ) relies on the ACC_SYNCHRONIZED implementation on the method modifier.

Synchronized code block: The monitorenter instruction is inserted into the beginning of the synchronized code block after compilation, and the monitorexit instruction is inserted into the end of the synchronized code block. The JVM needs to ensure that each monitorenter has A monitorexit corresponds to it. Any object has a monitor associated with it. When a monitor is held, it will be in a locked state. When the thread executes the monitorenter instruction, it will try to obtain the monitor ownership corresponding to the object, that is, try to obtain the lock of the object; [Excerpted from the Art of Concurrent Programming]

Synchronized method: The synchronized method will It is translated into ordinary method call and return instructions such as: invokevirtual and areturn instructions. There are no special instructions at the VM bytecode level to implement the method modified by synchronized. Instead, the method is added to the method table of the Class file. The synchronized flag position in the access_flags field is 1, indicating that the method is a synchronized method and uses the object that calls the method or the Class to which the method belongs to represent the Klass in the JVM's internal object as the lock object. (Excerpted from: http://www.cnblogs.com/javaminer/p/3889023.html)

The difference between synchronized and lock

What is the difference between synchronized and Lock?
The difference is as follows:

  • Source:
    lock is an interface, and synchronized is a keyword of java, synchronized is a built-in language implementation;

  • Whether to release the lock due to exception:
    synchronized will automatically release the lock it holds when an exception occurs, so there will be no deadlock; when an exception occurs in lock, it will not actively release the lock it holds, and you must manually unlock to release the lock. , which may cause deadlock to occur. (So ​​it is best to wrap the synchronization code block with try catch and write unlock in finally to avoid the occurrence of deadlock.)

  • Whether to respond to interrupt
    lock is waiting for the lock You can use interrupt to interrupt waiting, but synchronized can only wait for the lock to be released and cannot respond to interrupts;

  • Do you know whether to acquire the lock
    Lock can use trylock to know whether the lock has been acquired. Synchronized cannot;

  • Lock can improve the efficiency of read operations by multiple threads. (Read and write separation can be achieved through readwritelock)

  • In terms of performance, if the competition for resources is not fierce, the performance of the two is almost the same, and when the competition for resources is very fierce (that is, there is A large number of threads compete at the same time), at this time the performance of Lock is far better than synchronized. Therefore, it should be selected according to the appropriate situation when using it.

  • synchronized uses the wait, notify, and notifyAll scheduling mechanisms of the Object object itself, while Lock can use Condition to schedule between threads,

//Condition定义了等待/通知两种类型的方法
Lock lock=new ReentrantLock();
Condition condition=lock.newCondition();...condition.await();...condition.signal();
condition.signalAll();
Copy after login

1. The usage difference between synchronized and lock

synchronized: Add this control to the object that needs to be synchronized. Synchronized can be added to the method or to a specific code block, brackets Indicates the object that needs to be locked.

lock: Generally, the ReentrantLock class is used as the lock. The locking and unlocking locations need to be displayed through lock() and unlock(). Therefore, unlock() is generally written in the finally block to prevent deadlock.

2. The performance difference between synchronized and lock

synchronized is hosted for JVM execution,
and lock is the code written in java to control the lock.

In Java1.5, synchronize is performance inefficient. Because this is a heavyweight operation that requires calling the operation interface, locking may consume more system time than operations other than locking. In contrast, using the Lock object provided by Java has higher performance.

But with Java1.6, changes have taken place. Synchronize is very clear in semantics and can perform many optimizations, including adaptive spin, lock elimination, lock coarsening, lightweight locks, biased locks, etc. As a result, the performance of synchronize on Java1.6 is no worse than Lock. Officials also stated that they also support synchronize more and there is room for optimization in future versions.

The specific differences between the two mechanisms:
synchronized originally used the CPU pessimistic locking mechanism, that is, the thread obtains an exclusive lock. Exclusive lock means that other threads can only rely on blocking to wait for the thread to release the lock. When the CPU conversion thread is blocked, it will cause thread context switching. When there are many threads competing for the lock, it will cause frequent context switching of the CPU, resulting in very low efficiency.

Lock uses optimistic locking. The so-called optimistic locking is to complete an operation without locking each time but assuming that there is no conflict. If it fails due to a conflict, it will be retried until it succeeds. The mechanism implemented by optimistic locking is CAS operation (Compare and Swap). We can further study the source code of ReentrantLock and find that one of the more important methods of obtaining the lock is compareAndSetState. This is actually the special instruction provided by the called CPU.

Modern CPUs provide instructions that can automatically update shared data and detect interference from other threads, and compareAndSet() uses these instead of locks. This algorithm is called a non-blocking algorithm, which means that the failure or suspension of one thread should not affect the failure or suspension of other threads.

3. The difference between synchronized and lock usage

There is no difference between synchronized primitive and ReentrantLock under normal circumstances, but in very complex synchronization applications, please consider using ReentrantLock, especially when encountering the following two requirements.

1. A thread needs to be interrupted while waiting for control of a lock
2. Some wait-notify needs to be processed separately. The Condition application in ReentrantLock can control which thread to notify
3. With fair lock function, each incoming thread will queue up to wait.

Let’s talk about it in detail...

Let’s talk about the first case first. There are two lock mechanisms of ReentrantLock. , ignore interrupt locks and respond to interrupt locks, which gives us a lot of flexibility. For example: If two threads A and B compete for a lock, thread A obtains the lock and thread B waits. However, thread A really has too many things to deal with at this time and does not return. Thread B may not be able to wait any longer. I want to interrupt myself, stop waiting for this lock, and turn to other things. At this time ReentrantLock provides 2 mechanisms: interruptible/non-interruptible
First, the B thread interrupts itself (or other threads interrupt it), but ReentrantLock does not respond and continues to let the B thread Wait, no matter how you interrupt, I will ignore it (this is the synchronized primitive);
Second, the B thread interrupts itself (or other threads interrupt it), ReentrantLock handles the interrupt, and no longer waits for the lock Come, give up completely.

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of What is the difference between synchronized and Lock?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles