Sobes.tech
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:

  1. 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.
  2. Pessimistic Locking

    • Locks the resource during access to prevent conflicts.
    • Can be exclusive (write lock) or shared (read lock).
  3. Monitor (synchronized)

    • Built-in locking mechanism in Java.
    • Ensures that only one thread executes the block of code.
  4. ReentrantLock

    • More flexible lock from java.util.concurrent.locks.
    • Allows attempting to acquire the lock with a timeout, interrupting wait.
  5. 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.
  • synchronized is a simple built-in mechanism but less flexible.
  • ReentrantLock and ReadWriteLock provide extended lock management capabilities.

Example of using ReentrantLock:

ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
    // critical section
} finally {
    lock.unlock();
}