Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to lock a static variable in a non-static class?

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?

like image 266
Dario Solera Avatar asked Apr 01 '10 13:04

Dario Solera


People also ask

Can we use static variable in non static class?

“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.

Are static variables safe?

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.

Should static variables be avoided?

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.

Can we declare static variable in non static class in Java?

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 ...


1 Answers

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.

like image 68
Brian R. Bondy Avatar answered Sep 28 '22 03:09

Brian R. Bondy