Inspector puzzle with synchronization via a local variable

The inspector complains if you lock an object via a local reference. I
am curious why the IntelliJ team consider that a wicked or unusual
thing to do.

It seems to me the reference is irrelevant. The lock is on the object
pointed to, so it should not matter how you reference  it.

I am not complaining about this. I just want to understand the
Roedy Green Canadian Mind Products

If you tell a computer the same fact in more than one place, unless you have an automated mechanism to ensure           they stay in sync, the versions of the fact will eventually get out of sync.

Comment actions Permalink

The point was synchronization only makes sense if two different threads syncing on the same instance and question arises how safe was an exchange, that two threads have same reference on their stacks. Most obviously "clean" subject to synchronize on is a final field. Synchronizing on a local reference might well be not a problem but generally not that easy to verify for correctness and easy thing to broke later.

Comment actions Permalink

Because it doesn't generally make any sense to synchronize on a local variable since another thread can't access it. It isn't always wrong to sync on a local variable but isn't very common and any such code should be looked at closely for correctness.

The only time I have ever done it is when I was sync'ing on a Thread itself, Something like this:

          final Thread thread = Thread.currentThread();
            synchronized (this.waiters) {
                this.waiters.put(id, thread);              

          //Some code here that asynchronously sent a message off to another process
          synchronized (thread) {
                try {
                } catch (InterruptedException e) {
                    logger.warn("InterruptedException: ", e);

Then there was another thread running that would receive messages for this Thread and notify it when the response came back (with a correlation id).

If you think your local sync'ing is correct you can alt+enter on the warning, when the Inspection comes up press right arrow and select suppress for method or class. IntelliJ will add this annotation:



Please sign in to leave a comment.