Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between Lock and ReentrantLock in Java 5?

I don't understand the difference between them. I thought a lock from the lock interface was reentrant too then what's the difference between them? When would you use each?

like image 212
kale Avatar asked Apr 22 '16 16:04

kale


People also ask

What is ReentrantLock in Java?

A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.

What is difference between lock and synchronization in Java?

Major difference between lock and synchronized: with locks, you can release and acquire the locks in any order. with synchronized, you can release the locks only in the order it was acquired.

What is the difference between synchronized keyword and ReentrantLock?

In case of synchronized keyword, a thread can be blocked waiting for lock, for an indefinite period of time and there was no way to control that. ReentrantLock provides a method called lockInterruptibly(), which can be used to interrupt thread when it is waiting for lock.

What is the difference between the tryLock () and the regular lock () method in Java?

boolean tryLock() – This is a nonblocking version of lock() method. It attempts to acquire the lock immediately, return true if locking succeeds. boolean tryLock(long timeout, TimeUnit timeUnit) – This is similar to tryLock(), except it waits up the given timeout before giving up trying to acquire the Lock.


1 Answers

Lock is an interface. It defines a set of methods that all locks should have.

ReentrantLock is a concrete class that implements the Lock interface. It implements all the methods defined in Lock, plus much more. Additionally, as mentioned in the name, the lock is re-entrant which means the same thread can acquire the lock as many times as it wants. This is essentially the same behavior as the native object monitor locks provided by the synchronized keyword.

The Lock interface makes it possible for you to implement your own kind of lock. For example, you might design a lock that issues an HTTP request (performing network I/O) to lock a remote resource. Another class that uses your lock wouldn't care about the internal details of your lock; it only cares that your custom lock respects the Lock interface.

like image 125
Nayuki Avatar answered Oct 03 '22 07:10

Nayuki