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
objection.
--
Roedy Green Canadian Mind Products
http://mindprod.com

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.

2 comments

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.

0

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 {
                    thread.wait(timeout);
                } 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:

@SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"})

0

Please sign in to leave a comment.