VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-use-locks-in-multi-threaded-java-program/

⇱ How to Use Locks in Multi-Threaded Java Program - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Use Locks in Multi-Threaded Java Program

Last Updated : 24 Apr, 2026

In Java, a lock is a synchronization mechanism that ensures mutual exclusion for critical sections in a multi-threaded program. It controls access to shared resources, ensuring thread safety. Some locks, like

  • Exclusive Lock(ReentrantLock): Only one thread can acquire the lock at a time.
  • Shared Lock(ReadWriteLock): Multiple threads can hold the lock simultaneously under certain conditions.

Basic usage of a Lock:

Lock lock = new ReentrantLock();
lock.lock(); // Acquire the lock
// Critical section
lock.unlock(); // Release the lock

Types of Locks in Java

1. ReentrantLock

A ReentrantLock() is an implementation of Lock that allows a thread to reacquire the lock it already holds.

Output:

Thread-1 acquired lock
Thread-1 finished work
Thread-2 acquired lock
Thread-2 finished work

Explanation: Although both threads start together, one acquires the lock first while the other waits. After the lock is released, the waiting thread acquires it and proceeds.

2. ReadWriteLock

A ReadWriteLock allows multiple threads to read a resource concurrently, but only one thread to write, ensuring no reads happen during writing.


Output
Geek-1 added: Hi
Geek-2 added: Hello
Geek-1 read: Hi
Geek-2 read: Hello

Explanation: ReadWriteLock allows multiple threads to read simultaneously but only one thread to write at a time. This ensures safe and efficient access to shared data.

Methods in the Lock Interface

The Lock interface provides several methods for acquiring and releasing locks:

MethodDescription
void lock()Acquires the lock if available; blocks if the lock is held by another thread.
void lockInterruptibly()Acquires the lock unless the thread is interrupted while waiting.
void unlock()Releases the lock.
Condition newCondition()Returns a Condition object associated with the lock. Useful for wait/notify.
boolean tryLock()Attempts to acquire the lock immediately, returning true if successful.
boolean tryLock(long time, TimeUnit unit)Tries to acquire the lock within a specified timeout. Returns true if successful.


Comment