5

My application requires concurrent access to a data file using memory mapping. My goal is to make it scalable in a shared memory system. After studied the source code of memory mapped file library implementation, I cannot figure out:

  • Is it legal to read from a MappedByteBuffer in multiple threads? Does get block other get at OS (*nix) level?
  • If a thread put into a MappedByteBuffer, is the content immediately visible to another thread calling get?

Thank you.

To clarify a point: The threads are using a single instance of MappedByteBuffer, not multiple instances.

1 Answers1

1

Buffers are not thread safe and their access should be controlled by appropriate synchronisation; see the Thread Safety section in http://docs.oracle.com/javase/6/docs/api/java/nio/Buffer.html . ByteBuffer is a subclass of the Buffer class and therefore has the same thread safety issue.

Trying to make scalable the use of memory mapped files in a shared memory system looks highly suspicious to me. The use of memory mapped files is for performance. When you step into shared systems, looking for performance should be one thing to give a low priority at. Not that you should look for a slow system but you will have so many other problems that simply make it work should be your first (and only?) priority at the beginning. I won't be surprised if at the end you will need to replace your concurrent access to a data file using memory mapping with something else.

For some ideas like the use of an Exchanger, see Can multiple threads see writes on a direct mapped ByteBuffer in Java? and Options to make Java's ByteBuffer thread safe .

Community
  • 1
  • 1
SylvainL
  • 3,926
  • 3
  • 20
  • 24