My question refers to whether or not the use of a ReentrantLock guarantees visibility of a field in the same respect that the synchronized keyword provides.
For example, in the following class A, the field sharedData does not need to be declared volatile as the synchronized keyword is used.
class A { private double sharedData; public synchronized void method() { double temp = sharedData; temp *= 2.5; sharedData = temp + 1; } }
For next example using a ReentrantLock however, is the volatile keyword on the field necessary?
class B { private final ReentrantLock lock = new ReentrantLock(); private volatile double sharedData; public void method() { lock.lock(); try { double temp = sharedData; temp *= 2.5; sharedData = temp + 1; } finally { lock.unlock(); } } }
I know that using the volatile keyword anyway will only likely impose a miniscule performance hit, but I would still like to code correctly.
Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem.
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.
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.
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's safe without volatility. ReentrantLock
implements Lock
, and the docs for Lock
include this:
All
Lock
implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock, as described in The Java Language Specification, Third Edition (17.4 Memory Model):
- A successful
lock
operation has the same memory synchronization effects as a successfulLock
action.- A successful
unlock
operation has the same memory synchronization effects as a successfulUnlock
action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With