[concurrency-interest] Locking on local variables

Dmitry Zaslavsky dmitry.zaslavsky at gmail.com
Fri Jan 15 10:54:11 EST 2016


Object o = new Object();
synchronized(o){

}

The reason this code looks incorrect is that 'o' is not shared and not
known to any other thread.
Therefore you can't possibly be achieving any synchronization with any
other thread.

Consider slightly modified example

// Not local (outside of your function)
volatile Object lock = null;

// Local code
Object o = new Object();
synchronized(o){
  lock = o;
}

While this code has some other issues. At least it's potentially
meaningful. It will acquire the lock on 'o' and will publish it to the
outside world
Now some other thread can find and synchronize on it

Look at the next line in computeIfAbsent
It publishes that lock 'r' in casTabAt()


On Fri, Jan 15, 2016 at 10:21 AM, Sleiman Jneidi <jneidi.sleiman at gmail.com>
wrote:

> Hi everyone,
>
> From what I know, locking on local variables is useless, Brian Goetz in
> his book gave the following as an example of a bad lock
>
>  synchronized(new Object()){
>   ..
>  }
>
> So I assume, the code above is equivalent to the following
>
>   Object o = new Object();
>
>  synchronized(o){
>   ..
>  }
>
> However looking at ConcurrentHashMap#computeIfAbsent I see the following
>
> Node<K,V> r = new ReservationNode<K,V>();
>     synchronized (r) {
>     ...
>     }
>
> Just curious, why is that?
>
>
> Thanks
> Sleiman
>
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20160115/c44404c1/attachment-0001.html>


More information about the Concurrency-interest mailing list