• Post Reply Bookmark Topic Watch Topic
  • New Topic

Proper order for MonitorEnter/Exit?

 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looking at byte code generated for a synchronized block I see that the order seems to be (assuming I'm reading it right):



I had been doing it with the monitor enter/exit INSIDE the try block (and with a monitor exit inside the catch). Why is it better to put them outside a try...catch?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know. I would think that either approach would work. The important thing is to ensure you always MonitorExit, if you have done MonitorEnter.

There may be a reason for preferring the other way. Or it may be that the Java compiler writes had to pick from two equally-good options and happened to pick the other option to you.
 
Rob Spoor
Sheriff
Posts: 20817
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Slightly better:

That way it will always be called, whether the try block returns or throws an exception.

There are only two ways to skip a finally block:
- calling System.exit
- call some (native) code that will make your VM crash
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Er, no. We're talking about JNI here, so we're in C++. There's no "finally".
 
Dan Bizman
Ranch Hand
Posts: 387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Peter Chase:
I don't know. I would think that either approach would work. The important thing is to ensure you always MonitorExit, if you have done MonitorEnter.

There may be a reason for preferring the other way. Or it may be that the Java compiler writes had to pick from two equally-good options and happened to pick the other option to you.


Thanks, yeah I couldn't really see why it might be better. You're right, it's probably just diff. The important thing is that every "enter" call has an "exit" call too.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!