Week 66 — What is the purpose of the class `Lock` (in package `java.util.concurrent.locks`)?
Question of the Week #66
What is the purpose of the class
Lock
(in package java.util.concurrent.locks
)?3 Replies
The interface
Lock
can be used to limit concurrency. Threads can acquire locks and later release them.
Locks can be acquired using the lock()
method and released with unlock()
. A try
-finally
block should be used to ensure unlock
is called when the work using the lock is finished:
One important implementation of this class is ReentrantLock
which allows a thread to acquire the same lock multiple times but other threads cannot use it during that time:
It is also possible to create
Condition
s from a Lock
that allow waiting until they are told to continue execution by another thread.
Waiting for a condition can be done using the Condition#await
method which releases the lock, waits until another thread calls signal()
on that Condition
acquires the lock again.
It is possible to have multiple Condition
s for the same Lock
.📖 Sample answer from dan1st
"Lock" is an interface which locks concurrent access to a shared resource. At all it's used for a safe sync modification of objects. All code handled by lock should be covered with try-finally block. Someone prefers to use
synchronized
blocks, but locks are better, (personal opinion anyways) because you can actually use sync parted in a method. Also there's an ability to do a "test lock". We can execute tryLock() method to prevent locking method while it's used by another thread.
Submission from desinger