when thread 1 has the intrinsic lock of an object because of
synchronized(object) {
...
}
is it possible to call
object.method()
from thread 2 or not respectively do I need to type
synchronized(object) {
object.method();
}
in thread 2 to prevent it from calling the method while thread 1 is holding the lock?
In my case I got ConcurrentModificationExceptions while iterating over a Map and I tried to prevent modifications from other threads by locking the map. And I know that often the reason for ConcurrentModificationExceptions is that the map is changed during iteration but I’m quite sure that this is not the case in my case because there are only “get”-statements and one method call in the iteration, so there can’t happen any modification.
Thanks in advance.
Binabik
Synchronization in Java is entirely co-operative – if the second thread doesn’t choose to try to acquire the monitor (and if there’s nothing in the method which tries to do so) then it won’t automatically lock.
It’s not that the object “is locked” – it’s that one thread owns the lock associated with the object. The object itself can still be accessed; if it doesn’t need the lock, it won’t block.
Note that you can get a
ConcurrentModificationExceptioneven within a single thread if you try to iterate over it and change it within the same loop, e.g.It’s possible that this is what’s going on in your code, but we can’t tell as you haven’t shown us any code. If you can present a short but complete program demonstrating the problem, we’re much more likely to be able to work out what’s going on.