Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronized statements with "break"

I have used synchronized statements in my codec and there is a "break" in the block:

for (int j = 0; j < testPathSize; j++) {

  synchronized (lock) {
    if (kpis.get(j).getDate() > startTimeInMs) {

      if (j > 0) {
        if ((kpis.get(j).getDate() - startTimeInMs)
            > (startTimeInMs - kpis.get(j - 1).getDate())) initTestPath = j - 1;
        else initTestPath = j;
      } else initTestPath = j;

      break;
    }
  }
}

I want to know when break is executed, the "lock" will be released?

Thanks.

like image 753
gloria Avatar asked Jan 21 '26 11:01

gloria


2 Answers

Whenever execution goes outside the scope of the synchronized block, the lock will be released. No matter if it is because of normal program flow, a break, an exception, or any other way it goes outside of the block.

The official specification of how this works can be found in paragraph 14.19 The synchronized Statement in the Java Language Specification.

like image 181
Jesper Avatar answered Jan 24 '26 01:01

Jesper


It depends on where break takes your code:

  • If your loop that break ends is contained entirely within the synchronized block, then break will not release the lock, e.g.:

    synchronized (thing) {
        for (;;) {
            break;
        }
    }
    
  • Otherwise, execution will leave synchronized region, releasing the lock, e.g.:

    for (;;) {
        synchronized (thing) {
            break;
        }
    }
    

The rule is that the lock is released when you exit synchronized block for any reason, or call wait on the lock object.

Edit: Your code falls under the second category, when synchronized block is inside the loop. Therefore, break will release the lock.

like image 26
Sergey Kalinichenko Avatar answered Jan 24 '26 02:01

Sergey Kalinichenko



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!