Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java synchronize statement around a lock

I was wondering if

synchronize (lock) {
    ... 
}

Where lock is an instance of java.util.concurrent.locks.Lock, treats lock like any other object or as the try-finally idiom i.e.

 lock.lock(); 
 try {
     ... 
 } finally { 
    lock.unlock();
 }
like image 749
shikhar Avatar asked Jan 21 '26 04:01

shikhar


2 Answers

Lock documentation:

Note that Lock instances are just normal objects and can themselves be used as the target in a synchronized statement. Acquiring the monitor lock of a Lock instance has no specified relationship with invoking any of the lock() methods of that instance. It is recommended that to avoid confusion you never use Lock instances in this way, except within their own implementation.

So basically, it's treated as any other object. And, don't do that.

like image 130
Matthew Flaschen Avatar answered Jan 22 '26 18:01

Matthew Flaschen


It will treat the lock just like any other object.

like image 26
AgileJon Avatar answered Jan 22 '26 16:01

AgileJon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!