Movatterモバイル変換


[0]ホーム

URL:


Open In App

A lock is asynchronization mechanism that allows only one thread to access a shared object or class at a given time. When a thread acquires a lock, other threads attempting to access the same resource must wait until the lock is released.

  • Only one thread can hold the lock at a time; others wait until it’s released.
  • The Lock ensuresmutual exclusion for accessing shared resources.
  • Threads use lock.lock() to acquire and lock.unlock() to release after completion.
Lock
Lock

Types of Locks in Java

Locks in Java can be divided into two categories:

1. Intrinsic Locks

These are the locks automatically provided by Java’s synchronized keyword.

1.1 Object Locks

Anobject lock is acquired when a thread enters a synchronized instance method or block. It ensures that only one thread can access an object’s synchronized methods or blocks at a time.

Java
publicclassObjectLevelLock{publicsynchronizedvoiddisplay(){System.out.println(Thread.currentThread().getName()+" acquired object-level lock.");try{Thread.sleep(500);}catch(InterruptedExceptione){}}publicstaticvoidmain(String[]args){ObjectLevelLockobj=newObjectLevelLock();Threadt1=newThread(obj::display,"Thread-1");Threadt2=newThread(obj::display,"Thread-2");t1.start();t2.start();}}

Output:

output
output

Explanation: Here, ReentrantLock ensures that only one thread executes the critical section at a time. It must always be released in a finally block to avoid deadlocks.

1.2 Class-Level Lock

AClass-level lock is used to synchronize static methods or blocks. It locks the Class object (ClassName.class), so threads accessing the same class (even with different instances) must wait.

Java
publicclassClassLevelLock{publicstaticsynchronizedvoidshow(){System.out.println(Thread.currentThread().getName()+" acquired class-level lock.");try{Thread.sleep(500);}catch(InterruptedExceptione){}}publicstaticvoidmain(String[]args){Threadt1=newThread(ClassLevelLock::show,"Thread-1");Threadt2=newThread(ClassLevelLock::show,"Thread-2");t1.start();t2.start();}}

Output:

output
output

Explanation: Both threads try to access the same class-level synchronized method, so one must wait until the other releases the class-level lock. Even if new instances are created, they share the same class-level lock.

2. Explicit Locks (fromjava.util.concurrent.locks)

Unlike synchronized, explicit locks must be manually acquired and released, giving developers more flexibility and control.

2.1. ReentrantLock

AReentrantLock provides similar locking behavior as synchronized, but with more flexibility. The same thread can re-acquire the lock multiple times.

Java
importjava.util.concurrent.locks.ReentrantLock;publicclassReentrantLockExample{privatefinalReentrantLocklock=newReentrantLock();publicvoidtask(){lock.lock();try{System.out.println(Thread.currentThread().getName()+" acquired ReentrantLock.");}finally{lock.unlock();}}publicstaticvoidmain(String[]args){ReentrantLockExampleobj=newReentrantLockExample();newThread(obj::task,"Thread-1").start();newThread(obj::task,"Thread-2").start();}}

Output:

output
output

Explanation:Here, ReentrantLock ensures that only one thread executes the critical section at a time. It must always be released in a finally block to avoid deadlocks.

2.2. ReentrantReadWriteLock

ReentrantReadWriteLock Used when multiple threads read frequently but only a few write. It allows multiple readers or one writer at a time.

Java
importjava.util.concurrent.locks.ReentrantReadWriteLock;publicclassReadWriteLockExample{privatefinalReentrantReadWriteLockrwLock=newReentrantReadWriteLock();privateintdata=0;publicvoidwrite(){rwLock.writeLock().lock();try{data++;System.out.println(Thread.currentThread().getName()+" wrote: "+data);}finally{rwLock.writeLock().unlock();}}publicvoidread(){rwLock.readLock().lock();try{System.out.println(Thread.currentThread().getName()+" read: "+data);}finally{rwLock.readLock().unlock();}}publicstaticvoidmain(String[]args){ReadWriteLockExampleobj=newReadWriteLockExample();newThread(obj::write,"Writer").start();newThread(obj::read,"Reader-1").start();newThread(obj::read,"Reader-2").start();}}


Output:

output
output

Explanation: This example allows multiple readers to access data simultaneously, but only one writer at a time. Writers get exclusive access to prevent modification conflicts.

Commonly Used Lock Methods

MethodDescription
lock()Acquires the lock; blocks if not available.
unlock()Releases the lock.
tryLock()Attempts to acquire the lock without waiting.
lockInterruptibly()Acquires the lock unless interrupted.
isLocked()Checks if the lock is currently held.



Improve
Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp