开发者

Is it possible to call a method of a locked object from another thread?

开发者 https://www.devze.com 2023-04-10 16:34 出处:网络
when thread 1 has the intrinsic lock of an object because of synchronized(object) { ... } is it possible to call

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.开发者_StackOverflow社区 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 ConcurrentModificationException even within a single thread if you try to iterate over it and change it within the same loop, e.g.

// Not safe: will throw an exception
for (Map.Entry<String, String> entry : map.entrySet()) {
    if (entry.getKey().equals("foo")) {
        map.put("bar", "Hello");
    }
}

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.


When you acquire a lock, it only prevents other threads from acquiring the same lock. It does not lock the object as such and you can access its methods.

If you got a ConcurrentModicationException, then you have a concurrent modification. If you don't know where this is happening, you need to investigate further.


Unless object.method() is synchronized you can call it from an other thread. You have to be careful when using a iteration over a non-synchronized map. You should use a synchronzied map and synchronize over the iteration; otherwise you have to synchronize all write actions as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号