0

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);
        }
    }
1
  • You always can try it in code :) But yes, syncrhonized locks on the object instance (not the reference), because if you have 3 different references to the same instance, syncrhonizing on each one will block between the, Commented Feb 11, 2010 at 9:16

6 Answers 6

5

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)
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

2

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

Comments

1

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.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.