Interview question: lock VS synchronized

Purpose

It is convenient for me to review the follow-up interview, and I can record some of my study notes

resource

A learning video about high-frequency interview questions at Station B

comparative level

grammatical level

① synchronized is a keyword in JAVA, the source code is in JVM, implemented in C++ language
② Lock is an interface, the source code is provided by JDK, implemented in JAVA language
③ When using synchronized, the lock will be released automatically when exiting the synchronization code block , you need to manually call the unlock method to release the lock

functional level

① Both belong to pessimistic locks, both have basic mutual exclusion, synchronization, and lock reentry functions
② Lock provides many functions that synchronized does not have, such as obtaining waiting status, fair lock, interruptible, timeout, and multiple conditions Variable
③ Lock has implementations suitable for different scenarios, such as ReentrantLock, ReentrantReadWriteLock

performance level

① When there is no competition, synchronized has done a lot of optimizations, such as biased locks, lightweight locks, and the performance is not bad. ②
When the competition is fierce, the implementation of Lock usually provides better performance

Guess you like

Origin blog.csdn.net/xiaozhengN/article/details/127476662