Junior — Middle
How do lock types differ and how are they different from each other?
sobes.tech AI
Answer from AI
In Java, there are several types of locks that differ in their level of isolation and impact on concurrency:
-
Optimistic Locking
- Assumes that conflicts during data access are rare.
- Does not lock the resource during read, checks for changes during write.
- Used, for example, in JPA with versioning.
-
Pessimistic Locking
- Locks the resource during access to prevent conflicts.
- Can be exclusive (write lock) or shared (read lock).
-
Monitor (synchronized)
- Built-in locking mechanism in Java.
- Ensures that only one thread executes the block of code.
-
ReentrantLock
- More flexible lock from
java.util.concurrent.locks. - Allows attempting to acquire the lock with a timeout, interrupting wait.
- More flexible lock from
-
ReadWriteLock
- Allows multiple threads to read simultaneously, but write locks all.
Differences:
- Optimistic locks do not lock resources but check for changes upon commit.
- Pessimistic locks lock resources, preventing access by other threads.
synchronizedis a simple built-in mechanism but less flexible.ReentrantLockandReadWriteLockprovide extended lock management capabilities.
Example of using ReentrantLock:
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}