aultimus
aultimus

Reputation: 803

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.

Can someone tell me why a synchronized block is used, synchronizing on ReferenceQueue.class, instead of adding the synchronized qualifier to the method? 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();
    }
}

Upvotes: 0

Views: 338

Answers (1)

John Watts
John Watts

Reputation: 8885

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. 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.

Upvotes: 1

Related Questions