![]() |
VOOZH | about |
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
Basic usage of a Lock:
Lock lock = new ReentrantLock();
lock.lock(); // Acquire the lock
// Critical section
lock.unlock(); // Release the lock
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.
A ReadWriteLock allows multiple threads to read a resource concurrently, but only one thread to write, ensuring no reads happen during writing.
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.
The Lock interface provides several methods for acquiring and releasing locks:
| Method | Description |
|---|---|
| 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. |