[Logo]
Forums Register Login
synchronization and exception
From what i understand about synchronization,the following 2 ways of synchronizing an instance variable are equivalent:

Route 1:

void reverseOrder() {
synchronized (this) {
int halfWay = intArray.length / 2;
for (int i = 0; i < halfWay; ++i) {
.......
......
}
}
}

Route 2:

synchronized void reverseOrder() {

int halfWay = intArray.length / 2;
for (int i = 0; i < halfWay; ++i) {
i....
.......
}
}
}

If so,we can use these 2 techniques inter-changeably to protect the instance variable 'intArray'
Does anyone differ on this?

Now in either of these techniques,if we throw an exception mid-way,does the lock get released automatically?
Please, use code tags.

Yes, marking the method as synchronized and synchronizing the whole method body on this object has exactly the same result. And always when you return from a synchronized method or a synchronized block, the lock is released, no matter if it's a normal return or an exception.
You've gotta fight it! Don't give in! Read this tiny ad:
ScroogeXHTML 7.1 - RTF to HTML5 / XHTML converter
https://coderanch.com/t/690611/ScroogeXHTML-RTF-HTML-XHTML-converter


This thread has been viewed 749 times.

All times above are in ranch (not your local) time.
The current ranch time is
Feb 21, 2018 14:23:24.