How do memory mapped files work in a multiprocess scenario?

This question confused me for several days:

Suppose I have two processes ( p_writeand p_read) that run on the same machine.

  • The process is p_writedesigned to write / update mmap file.

  • The process is p_readintended to use the mmap file, or, in other words, to read from the mmap file.

My assumption is that p_writeyou must first allocate a memory space (off-heap) for the mmap file (the space is automatically mapped to the file using the Java API MappedByteBuffer).

My question is: how is p_read read from mmap file? My assumption now is that you p_readalso need to allocate another space with a bunch of the same size for the displayed mmap file, but this seems wrong, since the memory size in this scenario should be doubled.

If you p_readdo not need to allocate a separate memory space for the mmap file for matching, how p_readdoes it know the correct memory address to which the file was mapped using p_write?

UPDATE 1

I found a more suitable question, or you can consider it as the following question: If it FileChannel.map()is called twice, will the same file be displayed twice in two different memory spaces?

// Scenario A: In single process

try (FileChannel fc = FileChannel.open(filePath, openOptions)) {
   // First call
   fc.map(MapMode.READ_ONLY, 0, SIZE_CONSTANT);
   // Second call
   fc.map(MapMode.READ_ONLY, 0, SIZE_CONSTANT);
}

and

// Scenario B: In two processes

// in first process
try (FileChannel fc = FileChannel.open(filePath, openOptions)) {
   // First call in first process
   fc.map(MapMode.READ_WRITE, 0, SIZE_CONSTANT);
}
...
// in second process
try (FileChannel fc = FileChannel.open(filePath, openOptions)) {
   // Second call in second process
   fc.map(MapMode.READ_ONLY, 0, SIZE_CONSTANT);
}

Maybe this does not really matter for the two scenarios if they are all mapped to the same memory space?

+4

Source: https://habr.com/ru/post/1693218/


All Articles