questzen
questzen

Reputation: 3287

Java synchronization question

I was going through some code snippets looking at the synchronization aspect. I believe locking happens on objects. In the case of java we only have references to objects. Java should use the reference to procure the object and lock it.

What happens if the reference happens to be null? I feel this would break. If this were to work the locking needs to happen on references as well (which beats me). Can someone clarify this for me.

    synchronized (formatters) {
        if(formatters == null) {
            prepareCache(feedId);
        }
    }

Upvotes: 0

Views: 674

Answers (6)

Joe
Joe

Reputation: 913

From The synchronised Statement section in the Java Language Specification:

"SynchronizedStatement: synchronized ( Expression ) Block" ... Otherwise, if the value of the Expression is null, a NullPointerException is thrown."

Upvotes: 5

mfx
mfx

Reputation: 7388

It won't work. You synchronize on objects, not on variables. When the variable is null, there is no object to synchronize on, so an Exception is thrown.

Upvotes: 0

Thirler
Thirler

Reputation: 20760

Where possible don't synchronize on objects that are actually used. Synchronize on private final Objects that you create within the class that does the locking. Reason for this is that others might choose the same object to synchronize on, which means you have no idea what kind of side effects this locking has.

Upvotes: 1

Nate W.
Nate W.

Reputation: 9249

Sssh, you're not supposed to know those are actually references to objects! Think of them as they're presented - like an object - and not how they're implemented. The Object class provides a single lock, so your formatters object will have inherited it. If formatters happens to be null, then synchronizing on it will throw a NullPointerException.

Upvotes: 1

Hans W
Hans W

Reputation: 3891

You get a NullPointerException. For example:

class A {
    public static void main(String[] ss) {
        Object o = null;
        synchronized (o) {
        }
    }
}

Gives you:

Exception in thread "main" java.lang.NullPointerException
    at A.main(A.java:4)

Upvotes: 5

monksy
monksy

Reputation: 14234

According to this forum, and many other related links. If formatters is null, then the NullPointerException will be thrown.

Upvotes: 2

Related Questions