aspose file tools
The moose likes Threads and Synchronization and the fly likes synchronization and exception Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "synchronization and exception" Watch "synchronization and exception" New topic
Author

synchronization and exception

Ranadhir Nag
Ranch Hand

Joined: Mar 09, 2006
Posts: 138
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?
Adam Michalik
Ranch Hand

Joined: Feb 18, 2008
Posts: 128
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronization and exception
 
Similar Threads
synchronized void run()
Javini Multi Threading Tools 01
Why this synchronization doesn't work
Depth of Garbage Collection, Thread synchronization
Concurrency - why does yield() have no effect in this example?