When using something like this:
private final Object lock = new Object()
Is there any difference between static and non-static one?
Can non-static object lock static method or vice versa?
When using something like this:
private final Object lock = new Object()
Is there any difference between static and non-static one?
Can non-static object lock static method or vice versa?
If you're using a non-static lock, every instance of the object would have a different lock object, and it would be a potentially more fine grained equivalent of calling:
synchronized(this) {
}
That is to say: you're only locking against other accesses from within the same object. With a static lock, every instance of the class shares that lock object. So only one thread can access the synchronized block at any given time.
So it depends on what you're doing. In the former case, it doesn't make sense to bother allocating a lock object unless you have multiple of these locks protecting a smaller subset of the data. In the latter case, you're basically (again, more fine grained) doing this:
synchronized(MyObject.class) {
}
That is, you're locking against ALL accesses regardless of whether you have the same object or different ones doing the accessing.
It'll depend on what you're trying to accomplish, and what you're locking against, and how those locks are being used. If you're protecting per-instance state, you probably want a per instance (non-static) lock object. If you're protecting global state, you want a static lock object that's shared amongst everyone.
It depends, as always, on the situation. What is it you want to do? If a lock should be shared globally, it should probably be static. If what you're trying to synchronize is non-static, then you probably shouldn't use a static locking object as that would prevent simultaneous access to separate entities.
The big difference is that locking on a non-static object means that you might be locking on two different objects, thus not providing any mutual exclusion. If mutual exclusion needs to be provided only at the object level, then perhaps this is what you want. (This is, in fact, what's happening when you synchronize a (non-static) method: you are synchronizing on this
, which is definitely not a static object.)