简体   繁体   English

方法调用与同步块之间的“差距” —避免并发死锁

[英]“gap” between method call and the synchronized block — avoiding deadlock in concurrency

The following method is a method of class SomeType -- the type it is taking as its argument. 以下方法是SomeType类的方法-它作为其参数的类型。 The line comments indicate the line #s. 行注释指示行号。

synchronized void someMethod(SomeType other) {  // line 1
                                // line 2
    synchronized (other) {      // line 3
        //...do stuff           // line 4
    }
}

The block indicated as "line 4" has calls to some other synchronized methods of both this and other , and this code is intended for avoiding deadlocks. 指示为“第4行”的块调用了thisother一些其他同步方法,并且此代码旨在避免死锁。

However -- suppose both a.someMethod(b) and b.someMethod(a) are invoked concurrently, where a and b are different instances. 但是-假设同时a.someMethod(b)b.someMethod(a) ,其中ab是不同的实例。

Further suppose that b.someMethod(a) is invoked right after a.someMethod(b) is, and they both are held up at line 2-- each of a and b acquired its own lock and waiting for the other's lock to proceed. 进一步假设b.someMethod(a)被调用后立即a.someMethod(b)是,他们都在行举行了2--每ab获得自己的锁,并等待对方的锁进行。

Can/not this happen? 可以/不可以吗?

If so - on which jdk implementations? 如果是这样-在哪些JDK实现上? This looks like something that depends on the specific implementation unless it is explicitly in the jdk specifications. 除非依赖于jdk规范,否则这似乎取决于特定的实现。

TIA TIA

Yes, the deadlock you describe can happen. 是的,您描述的僵局可能会发生。 How often it happens may be dependent on the specifics of the threading code; 它发生的频率可能取决于线程代码的细节。 these days, you are most likely using the native threading of the operating system, so it would be more dependent on the native OS than on the JDK/JRE. 如今,您最有可能使用操作系统的本机线程,因此它将比JDK / JRE更依赖本机OS。 Deadlock is likely possible on most platforms, though, so you should guard against it in your code. 不过,在大多数平台上都有可能发生死锁,因此您应该在代码中加以防范。

If you think contention for the method will be low or if you don't care about performance, you could synchronize on a static member or on the class itself, rather than synchronizing on the objects. 如果您认为该方法的争用程度很低,或者您不关心性能,则可以在静态成员或类本身上进行同步,而不是在对象上进行同步。 If you do care about performance and think contention will be significant, you will need to figure out a way to ensure that the monitors are locked in the same order independent of which object the method is being called on and which is the method argument. 如果您确实关心性能,并且认为争用会很重要,那么您将需要找出一种方法,以确保监视器以相同的顺序锁定,而与调用该方法的对象以及方法的参数无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM