3

I am using JDK20's FFI, and I need to pass a Object to a BlockingQueue to shared it from one thread to another. The Object contains several MemorySegment field, which belongs to Arena.openShared(). Before passing, I write some bytes into the MemorySegment using MemorySegment.set(JAVA_BYTE, ..., ...). I don't know if the other thread would read exactly what I write, since I am not using VarHandle.setVolatile() to ensure its thread visibility. But as Java Objects, there should be locks in BlockingQueue to ensure it, I wonder if it's also appliable to the MemorySegment, that each byte would be flushed to the memory for other threads to see them.

benrush
  • 43
  • 4

1 Answers1

2

If you look at the Specification for BlockingQueue, you can find the following paragraph:

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.

As BlockingQueue establishes a happen-before relationship, no additional synchronization is needed.

Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
  • 2
    Note that there’s an [API Note](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/lang/foreign/package-summary.html#:~:text=of%20this%20API.-,API%20Note,-%3A) saying “*Usual memory model guarantees, for example stated in 6.6 and 10.4, do not apply when accessing native memory segments as these segments are backed by off-heap regions of memory.*” but considering which chapters have been linked, I have the feeling that the author of this sentence uses the term “memory model” wrongly, as these chapters have nothing to do with the JMM. – Holger Aug 28 '23 at 08:56
  • Access control? Array access? How is that relevant for the memory model? Does that sentence mean I need to add specific synchronization mechanism to off-heap memory, as "Usual memory model guarantees" do not apply? What are those alternatives? – Johannes Kuhn Aug 28 '23 at 11:37
  • 2
    It irritates me as well. That’s why I said, I have the feeling, the author of the sentence uses the term “memory model” wrongly. I think, we have to request clarification from the JDK developers. – Holger Aug 28 '23 at 12:18