I've got a class that manages a shared resource. Now, since access to the resource depends on many parameters, this class is instantiated and disposed several times during the normal execution of the program.
The shared resource does not support concurrency, so some kind of locking is needed. The first thing that came into my mind is having a static instance in the class, and acquire locks on it, like this:
// This thing is static!
static readonly object MyLock = new object();
// This thing is NOT static!
MyResource _resource = ...;
public DoSomeWork() {
lock(MyLock) {
_resource.Access();
}
}
Does that make sense, or would you use another approach?
“Can a non-static method access a static variable or call a static method” is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.
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.
Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.
The static variables can be accessed in the static methods only if we try to access the non-static variables in the static method compiler will show an error because non-static variables can only access by creating an instance of the class only but static methods can be called without creating an instance of the class ...
Yes you can use a static variable to protect a shared resource.
You could also use typeof(class) as the expression inside lock. See the warning below though, with the static variable it is at least more protected to within your class.
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