What is Lock in java Thread and types of Lock

What is Lock in java Thread and types of Lock –

java.util.concurrent.locks.Lock

Lock in multiple threading provide more extensive locking operations than the internal lock used by synchronized methods and blocks.

A lock is a tool for controlling access to a resource that shared by multiple threads. It guarantees that only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, such as the read lock of a ReadWriteLock.

public interface Lock

Methods of lock interface –

  • void lock() – Acquires the lock.
  • void lockInterruptibly() – Acquires the lock unless the current thread is interrupted.
  • Condition newCondition() – Returns a new Condition instance that is bound to this Lock instance.
  • boolean tryLock() – Acquires the lock only if it is free at the time of invocation.
  • boolean tryLock(long time, TimeUnit unit) – Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted.
  • void unlock() – Releases the lock.

There are three types of locks – ReentrantLock, ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock. All these three locks implements Lock interface.

Lock provides more flexibility and removes block-structured locking(used with synchronized). Its make it possible for automatic release of locks.

codelock

Gopal Das
Follow me

Gopal Das

Founder at GopalDas.Org
He is a technology evangelist, Salesforce trainer, blogger, and working as a Salesforce Technical Lead. After working in Java based project implementation, he jumped to the Salesforce system on a whim and never looked back. He fell in love with Salesforce’s flexibility, scalability, and power. He expanded his knowledge of the platform and became a Certified App Builder, Administrator, Platform Developer I, SalesCloud Consultant while leading the Salesforce implementation and technology needs. He has worked in a wide variety of applications/services like desktop, web and mobile applications.
Gopal Das
Follow me

Leave a Reply

Your email address will not be published. Required fields are marked *