Home  >  Article  >  Java  >  What are the common locks in Java?

What are the common locks in Java?

王林
王林Original
2019-11-20 17:43:348181browse

What are the common locks in Java?

Fair lock/unfair lock

Fair lock means that multiple threads apply for locks according to order to acquire the lock.

Unfair lock refers to the order in which multiple threads acquire locks, 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 , which will cause priority inversion or starvation.

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.

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, and 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.

Recommended tutorial: java introductory tutorial

The above is the detailed content of What are the common locks in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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