jni/java:有效安全地不变本机对象的线程安全发布/共享 [英] jni/java: thread safe publishing/sharing of effectively immutable native object
问题描述
1)我有一个本地java函数,该函数传递几个参数,并且其实现是一个本地C ++构造函数,用于创建对象并返回从指针到对象的强制转换的long.该对象的构造成员实际上是不可变的.然后,C ++对象可以根据其构造状态进行工作.
1) I have a native java function which passes several params and its implementation is a native C++ constructor to create an object and returns a long which is cast from the pointer to object. This object's constructed members are effectively immutable. The C++ object then can do work based on its constructed state.
2)获得函数调用结果的Java代码将指针的加长版本安全地发布到某个地方(没有互斥锁),并更改一个volatile变量,以希望将本机C ++对象中的内存更改发布到其他线程
2) java code that gets the result of the function call safely publishes the longified version of the pointer somewhere (without mutex) and changes a volatile variable to hopefully publish the memory changes in the native C++ object to other threads
现在,另一个线程读取该可变变量2),然后选择已发布的变量,然后调用另一个本机函数,该函数访问C ++内存空间中有效的不可变对象以完成某些工作.
Now another thread reads that volatile 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 work.
问题:由于Java内存模型对volatile和fence的保证,其他线程是否保证可以看到完全构造的本机对象?我敢肯定,在某些平台上答案是肯定的,但是我看到使用围栏时不同的芯片以不同的方式工作,并且想知道所有可使用Java的平台.
Question: 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 in different ways with using fences, and was wondering about all platforms for which java is available.
推荐答案
JCIP的合著者回答了JSR邮件列表上的并发问题.
A co-author of JCIP answered the question on the JSR mailing list for concurrency.
他说:"JMM [不做任何保证]扩展到Java堆之外的任何内容-更具体地说,它仅适用于Java字段",但实际上,当今使用的障碍/栅栏是粗粒度的,并且会影响所有内存均等",因此在实践中(只要您使用正常的进程内存,此问题中描述的易失性发布尝试就可以正常工作").
He says: "JMM [makes no] guarantees extending to anything outside the Java heap - or more specifically it only applies to Java fields", but that "In practice the barriers/fences used today are coarse-grained and will affect all memory equally", so "that in practice this [the volatile publishing attempt described in the question] will work fine (as long as you are using normal process memory)".
邮件列表中的另一位受访者说:我们中的某些人绝对认为这是确保Java,C和C ++同步按预期工作的目标,而Java同步为C或C ++变量提供了正确的可见性保证,相反",但补充说没有[行为]的书面保证."
Another respondent on the mailing list says: "Some of us have definitely considered it a goal to ensure that Java, C, and C++ synchronization works together as expected, with Java synchronization providing the right visibility guarantees for C or C++ variables, and conversely" but adds that "there is no written guarantee of that [behavior]".
这篇关于jni/java:有效安全地不变本机对象的线程安全发布/共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!