views:

86

answers:

1

I have some objective-c code that uses an NSLock to implement a sort of transaction. The object is locked on a "begin transaction", several other calls are made with the lock in place, and then it's released with a "commit". I'm writing a JNI glue layer to access this code from Java, but the lock is behaving differently in JNI vs pure objc code.

I have unit tests in both Java and objc that exercise the code that makes the lock. The objc test passes, but in the Java test [anNSLock tryLock] returns false even though [anNSLock lock] hasn't been called.

Is there a recommended way to have a mutex in JNI? I'm not sure what the underlying mechanism for NSLock is.

Thanks!

+1  A: 

The docs for NSLock says that NSLock uses Posix threads. Does Java use Posix threads?

A couple of alternative: The first is to create a synchronized wrapper in Java for your object. The second is to use the JNI MonitorEnter and MonitorExit methods for synchronization.

jdigital
Thanks for the suggestions. I think the page below will be helpful, as it talks about mutexes in addition to MonitorEnter, etc.http://java.sun.com/docs/books/jni/html/other.htmlI think my question was a little unclear (synchronize is probably out as a solution, but monitor enter / exit could work). I rewrote the first part to read:'I have some objective-c code that uses an NSLock to implement a sort of transaction. The object is locked on a "begin transaction", several other calls are made with the lock in place, and then it's released with a "commit".'
dacc
Are you allowing access from Java and non-Java threads?
jdigital
Only from Java threads.
dacc
Then MonitorEnter and MonitorExit should do the job for you.
jdigital
Awesome, thanks again!
dacc