Can BlockingQueue make MemorySegment visible for multiple threads?

128 views Asked by At

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

There are 1 answers

3
Johannes Kuhn On

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.