Reputation: 4198
I find a code snippet that works fine till lock is at Object level and when the same lock is made static final ( i.e static keyword is added ) , code starts failing with concurrency related errors.
Should a lock that works at object level reamin working once its scope is made static ? I thought making a lock as static will only make it more restrictive and should not start causing any more concurrencyissues than when it was at object level. I am finding the converse happening however.
Upvotes: 1
Views: 608
Reputation: 1250
A lock at static level would be more likely to be shared between different threads than a lock at object level (in a very general kind of way - since it depends on the actual code and threads involved).
In practice a static lock is associated with the class, in other words the single lock object is shared between all threads. Usually as more threads needs access to the same lock the more likely you are to run into concurrency problems (like deadlocks and starvation) if there is a bug in the code.
As a generalization, if you ran into concurrency problems using object level locks, you're probably going to have even more trouble when promoting the locks to class level instead.
Upvotes: 0
Reputation: 116858
Should a lock that works at object level reamin working once its scope is made static ?
If you move a lock from being an instance lock to be a static lock, it should not cause concurrency issues. You are correct that it should make the code more restrictive in that a single lock will be used instead of multiple instance locks. This is, of course, if the lock in question is static final
and all of the places in your code are appropriately locking it.
public static final Object lockObject = new Object();
What may be happening is that moving the lock has uncovered a bug that was there previously but application timing was causing it to be hidden. By locking on a static
lock (or on a static
method) the timing of the threads in your application will most likely be significantly changed.
If you post more details about the code or the errors that you are getting, we can provide better answers.
Upvotes: 1