Can multiple threads see writes on a direct mapped ByteBuffer in Java?

前端 未结 7 2038
小鲜肉
小鲜肉 2020-12-08 07:31

I\'m working on something that uses ByteBuffers built from memory-mapped files (via FileChannel.map()) as well as in-memory direct ByteBuffers. I am trying to understand th

相关标签:
7条回答
  • 2020-12-08 08:22

    The cheapest thing you can do is use a volatile variable. After a thread writes to the mapped area, it should write a value to a volatile variable. Any reading thread should read the volatile variable before reading the mapped buffer. Doing this produces a "happens-before" in the Java memory model.

    Note that you have NO guarantee that another process is in the middle of writing something new. But if you want to guarantee that other threads can see something you've written, writing a volatile (followed by reading it from the reading thread) will do the trick.

    0 讨论(0)
提交回复
热议问题