When implementing a lock, I used to create a private object inside of my class:
If I want to be sure that it is locked in the thread that created my class:
private object Locker = new object();
If I want to be sure that it will be locked for all threads inside my application:
private static object Locker = new object();
But here: Why does the lock object have to be static?
and in a number of other questions, everyone says that the object has to be readonly
. I haven't found the reason - not even in MSDN or JavaDoc.
As I use this kind of construction quite often, could someone explain to me why should I use readonly
?
Thanks!
depends on how you use and read it. if your read is atomic (i.e, won't be interrupted by write) and the read thread does not have dependency with the write threads, then you maybe able to skip read lock. But if your 'read' operation takes some time and takes heavy object interation, then you should lock it for read.
Lock Object is a feature offered by ABAP Dictionary that is used to synchronize access to the same data by more than one program. Data records are accessed with the help of specific programs. Lock objects are used in SAP to avoid the inconsistency when data is inserted into or changed in the database.
A Lock object can not be acquired again by any thread unless it is released by the thread which is accessing the shared resource. An RLock object can be acquired numerous times by any thread. A Lock object can be released by any thread. An RLock object can only be released by the thread which acquired it.
If I want to be sure that it will be locked for all threads inside my application:
The lock object has to be static, if it locks access to static state.
Otherwise it has to be instance, because there's no need to lock state of one class instance, and prevent other threads to work with another class instance at the same time.
everyone says that the object has to be "readonly" I didn't found the reason
Well, it doesn't have to be. This is just a best practice, which helps you to avoid errors.
Consider this code:
class MyClass { private object myLock = new object(); private int state; public void Method1() { lock (myLock) { state = // ... } } public void Method2() { myLock = new object(); lock (myLock) { state = // ... } } }
Here Thread1 can acquire lock via Method1
, but Thread2, which is going to execute Method2
, will ignore this lock, because lock object was changed => the state can be corrupted.
It doesn't have to be readonly, but it's good practise to as it saves you from accidentally replacing it, which can lead to some difficult to track down bugs.
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