[concurrency-interest] jni effectively immutable "constructor" guarded by java volatile for safe publishing

Andy Nuss andrew_nuss at yahoo.com
Mon Aug 27 13:16:37 EDT 2012


1) I have a native function which passes several params and uses a native 
C++ constructor in-place constructor relative to a saved nio direct bytebuffer to create an object,  returning a long which is cast from 
the pointer to object.  This object's constructed values are effectively immutable in that only that native call sets the members of the obect.  The C++ object then can do work based on its constructed state.

2) java code that makes the above calls safely publishes the longified version of the C++ pointer (created above)
somewhere (without mutex) and changes a volatile variable to hopefully 
publish the memory changes made in the "constructor" above to other threads.

 another java thread reads that volatile fence variable of 2), and then picks up 
that published long, and calls another native function that accesses 
that effectively immutable object in the C++ memory space to do some 

Is that other thread guaranteed to see the fully constructed native 
object because of the Java Memory Model guarantees about volatiles and 
fences?  I would bet the answer is yes on some platforms, but I see that
 different chips work different ways with using fences, and was 
wondering about all platforms for which java is available.  I couldn't 
tell by googling whether the Java Memory Model made guarantees relative 
to changes in *all* memory, not just that of the virtual machine.  Maybe sun.misc.Unsafe might come to the rescue?

 the way, I need to use mutexes in my native code too for the purpose of subdividing the nio bytebuffer of 1), and found that 
JNI MontorEnter() was extraordinarily slow, as are all callbacks into 
java code.  I saw somewhere that it is safe to use POSIX threads' or 
Windows threads' semaphores as long as during the critical section, 
there are no callbacks into jvm.  But I wonder if anyone can answer this other question?)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20120827/ffaa9039/attachment.html>

More information about the Concurrency-interest mailing list