[英]Static synchronized method vs static method with all the code in a synchronized block
The following code snippet is taken from android JellyBean ReferenceQueue.java in the libcore project. 以下代码段摘自libcore项目中的android JellyBean ReferenceQueue.java。
Can someone tell me why a synchronized block is used, synchronizing on ReferenceQueue.class, instead of adding the synchronized qualifier to the method? 有人可以告诉我为什么要使用同步块,在ReferenceQueue.class上进行同步,而不是将同步限定符添加到方法中吗? Are these two approaches functionally equivalent in this instance?
在这种情况下,这两种方法在功能上是否等效?
From similar questions that I looked at it seems to be more efficient to make the method synchronized. 从我看过的类似问题来看,使方法同步似乎更有效。
Cheers, Matt 干杯,马特
public class ReferenceQueue<T> {
... <snip> ...
public static Reference unenqueued = null;
static void add(Reference<?> list) {
synchronized (ReferenceQueue.class) {
if (unenqueued == null) {
unenqueued = list;
} else {
Reference<?> next = unenqueued.pendingNext;
unenqueued.pendingNext = list.pendingNext;
list.pendingNext = next;
}
ReferenceQueue.class.notifyAll();
}
}
They are exactly equivalent except for the method signature. 除了方法签名外,它们完全等效。 When you make a static method synchronized it is the same as synchronizing the full body of the method on the class token.
使静态方法同步时,与在类令牌上同步方法的整个主体是相同的。 When you make a non static method synchronized it is the same as synchronizing on the this pointer.
使非静态方法同步时,与在this指针上同步相同。 The method signature difference is rarely relevant but for instance it can be a compiler warning to override a synchronized method and make the overriding method unsychronized.
方法签名的差异很少相关,但是例如,它可能是编译器警告,它覆盖同步的方法并使覆盖的方法不同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.