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);
        }
    }
Was it helpful?

Solution

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

OTHER TIPS

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)

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

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top