亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java Javagetting Started What are the differences between java locks?

What are the differences between java locks?

Nov 12, 2019 pm 04:31 PM
java the difference Lock

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!

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

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

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

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.

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

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;

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

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

How to obtain digital currency BTC? What are the differences between btc and digital currency? How to obtain digital currency BTC? What are the differences between btc and digital currency? Aug 01, 2025 pm 11:15 PM

There are four main ways to obtain BTC: 1. Register and exchange it with fiat currency or other digital assets through centralized trading platforms such as Binance, OK, Huobi, and Gate.io; 2. Participate in P2P platforms to directly trade with individuals, and pay attention to the credit risks of the counterparty; 3. Provide goods or services to accept BTC as payment; 4. Participate in airdrops, competitions and other platform reward activities to obtain a small amount of BTC. The core difference between BTC and digital currency is: 1. BTC is a type of digital currency, which belongs to a genus relationship; 2. BTC adopts a proof of work (PoW) mechanism, while other digital currencies may use various technologies such as proof of stake (PoS); 3. BTC emphasizes the value storage function of "digital gold", and other digital currencies may focus on payment efficiency or

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

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.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

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

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

See all articles