synchronized native method causes lock to be released
I've a synchronized method which calls a native synchronized method. On return from the native method the lock acquired on the object is lost. This causes IllegalMonitorStateException when the method is returned. I've pasted the code below. Has anyone else experienced this? I've tried with 1.4.2 and 1.5. Both have the same issue.
publicfinalclass TestOrder{
protectedsynchronizednativeint getOrderById(String orderId,byte[] buffer);
publicsynchronized Order getOrder(String orderId){
System.out.println("1. Holds lock = " + (Thread.holdsLock(this) ?"True" :"False"));
byte[] buffer =newbyte[1000];
getOrderById(orderId, buffer);
System.out.println("2. Holds lock = " + (Thread.holdsLock(this) ?"True" :"False"));
returnnew Order(buffer);
}
}
Message was edited by:
alok_s
Message was edited by:
alok_s
[1735 byte] By [
alok_sa] at [2007-11-27 5:47:36]

# 1
> I've a synchronized method which calls a native
> synchronized method. On return from the native method
> the lock acquired on the object is lost. This causes
> IllegalMonitorStateException when the method is
> returned. I've pasted the code below. Has anyone else
> experienced this? I've tried with 1.4.2 and 1.5. Both
> have the same issue.
On my Linux box using 1.6.0_01, 1.5.0_11 and 1.4.2_14 the output is:
1. Holds lock = True
2. Holds lock = True
as expected.
Jim S.
# 2
Here's a guess that would explain the behaviour:
the native method code tries to synchronize on the instance using MonitorEnter/MonitorExit. Maybe there is some execution path that makes it call MonitorExit one more time than MonitorEnter.
If this is the case, you may just remove any synchronization from the native code, Since the native method has already been declared synchronized.
# 3
Yes, it works fine if I remove Synchronized from the native method. It isn't really necessary given that the Java method is synchronized(as you pointed out).
You make a good suggestion about checking the native method to see if it does any monitorexit/monitorenter. I suspect that could be the case and hopefully it will remove my doubts about Java going wrong here.
Thanks.