What are the differences between java locks?
Fair lock/unfair lock
Fair lock means that multiple threads acquire the lock in the order in which they apply for it Lock.
Unfair lock means that the order in which multiple threads acquire locks is not in the order in which they apply for locks. It is possible that the thread that applies later acquires the lock before the thread that applies first. It is possible that it will cause priority inversion or starvation.
For Java ReentrantLock, specify whether the lock is a fair lock through the constructor, and the default is an unfair lock. The advantage of unfair locks is that the throughput is greater than fair locks.
For Synchronized, it is also an unfair lock. Since it does not implement thread scheduling through AQS like ReentrantLock, there is no way to turn it into a fair lock.
Reentrant lock
Reentrant lock, also known as recursive lock, means that when the same thread acquires the lock in the outer method, it enters the inner method The lock will be acquired automatically. It's a bit abstract, but there is a code example below.
For Java ReentrantLock, its name can be seen as a reentrant lock, and its name is Re entrant Lock.
For Synchronized, it is also a reentrant lock. One benefit of reentrant locks is that deadlocks can be avoided to a certain extent.
synchronized void setA() throws Exception{ Thread.sleep(1000); setB(); } synchronized void setB() throws Exception{ Thread.sleep(1000); }
The above code is a feature of a reentrant lock. If it is not a reentrant lock, setB may not be executed by the current thread, which may cause a deadlock.
Exclusive lock/shared lock
Exclusive lock means that the lock can only be held by one thread at a time.
Shared lock means that the lock can be held by multiple threads.
For Java ReentrantLock, it is an exclusive lock. But for another implementation class of Lock, ReadWriteLock, its read lock is a shared lock and its write lock is an exclusive lock.
The shared lock of the read lock can ensure that concurrent reading is very efficient, and the processes of reading, writing, writing, and writing are mutually exclusive.
Exclusive locks and shared locks are also implemented through AQS. Exclusive or shared locks are implemented through different methods.
For Synchronized, of course it is an exclusive lock.
Mutual Exclusion Lock/Read-Write Lock
The exclusive lock/shared lock mentioned above is a broad term, and the mutex lock/read-write lock is specific realization.
The specific implementation of mutex lock in Java is ReentrantLock.
The specific implementation of read-write lock in Java is ReadWriteLock.
Optimistic Lock/Pessimistic Lock
Optimistic lock and pessimistic lock do not refer to specific types of locks, but to the perspective of viewing concurrency and synchronization.
Pessimistic lock believes that concurrent operations on the same data will definitely be modified. Even if there is no modification, it will be considered modified. Therefore, for concurrent operations on the same data, pessimistic locking takes the form of locking. Pessimistically, I believe that concurrent operations without locking will definitely cause problems.
Optimistic locking believes that concurrent operations on the same data will not be modified. When updating data, the data will be updated by trying to update and constantly re-updating the data. Optimistically, there will be no problem with concurrent operations without locking.
We can see from the above description that pessimistic locking is suitable for scenarios with a lot of write operations, and optimistic locking is suitable for scenarios with a lot of read operations. Not locking will bring a lot of performance improvements.
The use of pessimistic locking in Java is to use various locks.
The use of optimistic locking in Java is lock-free programming, and the CAS algorithm is often used. A typical example is the atomic class, which implements the update of atomic operations through CAS spin.
Segmented lock
Segmented lock is actually a lock design, not a specific lock. For ConcurrentHashMap, its concurrency implementation is Efficient concurrent operations are achieved through segmented locks.
Let’s take ConcurrentHashMap to talk about the meaning and design ideas of segment lock. The segment lock in ConcurrentHashMap is called Segment, which is similar to the structure of HashMap (the implementation of HashMap in JDK7 and JDK8), that is, the internal There is an Entry array, and each element in the array is a linked list; it is also a ReentrantLock (Segment inherits ReentrantLock).
When it is necessary to put an element, it does not lock the entire hashmap, but first uses the hashcode to know which segment it should be placed in, and then locks this segment, so when When multi-threaded put, as long as it is not placed in a segment, true parallel insertion is achieved.
However, when counting size, when obtaining the global information of hashmap, you need to obtain all segment locks to count.
The design purpose of segmented lock is to refine the granularity of the lock. When the operation does not need to update the entire array, only one item in the array is locked.
Bias lock/Lightweight lock/Heavyweight lock
These three types of locks refer to the status of the lock and are for Synchronized. In Java 5, efficient Synchronized is achieved by introducing a lock upgrade mechanism. The status of these three locks is indicated by the fields in the object header of the object monitor.
Biased lock means that a piece of synchronization code is always accessed by one thread, then the thread will automatically acquire the lock. Reduce the cost of acquiring locks.
Lightweight lock means that when the lock is a biased lock and is accessed by another thread, the biased lock will be upgraded to a lightweight lock. Other threads will try to acquire the lock through spin without blocking. , improve performance.
Heavyweight lock means that when the lock is a lightweight lock, although another thread is spinning, the spin will not continue forever. When it spins a certain number of times, it has not been acquired yet. lock, it will enter blocking, and the lock will expand into a heavyweight lock. Heavyweight locks will block other application threads and reduce performance.
Spin lock
In Java, a spin lock means that the thread trying to acquire the lock will not block immediately, but will use a loop to try to acquire the lock. , the advantage of this is to reduce the consumption of thread context switching, but the disadvantage is that the loop consumes CPU.
php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!
The above is the detailed content of What are the differences between java locks?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

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)

Hot Topics



In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

char and unsigned char are two data types that store character data. The main difference is the way to deal with negative and positive numbers: value range: char signed (-128 to 127), and unsigned char unsigned (0 to 255). Negative number processing: char can store negative numbers, unsigned char cannot. Bit mode: char The highest bit represents the symbol, unsigned char Unsigned bit. Arithmetic operations: char and unsigned char are signed and unsigned types, and their arithmetic operations are different. Compatibility: char and unsigned char

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Although C and C# have similarities, they are completely different: C is a process-oriented, manual memory management, and platform-dependent language used for system programming; C# is an object-oriented, garbage collection, and platform-independent language used for desktop, web application and game development.

Detailed explanation of XPath search method under DOM nodes In JavaScript, we often need to find specific nodes from the DOM tree based on XPath expressions. If you need to...

Multithreading is an important technology in computer programming and is used to improve program execution efficiency. In the C language, there are many ways to implement multithreading, including thread libraries, POSIX threads, and Windows API.
