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.

1 Answer 1

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.

3
  • 2
    Note that there’s an API Note 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
    Commented Aug 28, 2023 at 8: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? Commented Aug 28, 2023 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
    Commented Aug 28, 2023 at 12:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.