What is the difference between synchronized and Lock?
Nov 19, 2020 am 11:38 AMDifference: 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.
#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){ } } }
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
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
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();
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used
