Search code examples
javamemory-mapped-files

Are memory mapped files managed by the OS?


I have been reading about memory mapped files and I had a couple of questions:

  1. Are they operating system managed or do they exist within the JVM heap and therefore are subject to garbage collection.
  2. If they are operating system managed, and I know this is OS dependent, but is it likely that if I have two processes (Java or not) that memory map a file, that they are going to be looking at the same bit of memory. (ie. Given a 1MB file, if 10 processes memory map it, it still only uses ~1MB of memory)

Solution

  • The exact implementation of memory mapped files is intentionally unspecified but the obvious intention is that if the operating system provides such a capability, it is used for implementing it.

    Thus, for most operating systems and JVMs, the MappedByteBuffer is just a wrapper around the logical memory returned by the operating system’s function for memory mapping. It is still subject to garbage collection; if the last front end byte buffer pointing to the mapped region got collected, the implementation will take care to release the mapping.

    If the operating system provides shared access to a file region via the same physical memory page, the typical Java implementations of memory mapped files will exhibit that behavior. This is in fact the most straight-forward way of implementing shared memory between processes in Java; just letting each process map the same region of the same temporary file…