A couple of times I have came across this code where a local variable in a class ( its NOT a static variable) has been used in a lock.
public class SomeClass
{
private object obj = new object();
....
....
lock(obj)
{
}
}
Is there any point of locking given that its an instance variables?
Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.
Instance variables are non-static variables and are declared in a class but outside any method, constructor or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods. However, non-static methods have access to all variables (instance or static) and methods (static or non-static) in the class.
Is there any point of locking given that its an instance variables?
Multiple threads could be acting on the same instance and a lock is needed for thread-safety. Think, for example, of a shared queue.
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