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
I would assume that direct memory provides the same guarantees or lack of them as heap memory. If you modify a ByteBuffer which shares an underlying array or direct memory address, a second ByteBuffer is another thread can see the changes, but is not guaranteed to do so.
I suspect even if you use synchronized or volatile, it is still not guaranteed to work, however it may well do so depending on the platform.
A simple way to change data between threads is to use an Exchanger
Based on the example,
class FillAndEmpty {
final Exchanger<ByteBuffer> exchanger = new Exchanger<ByteBuffer>();
ByteBuffer initialEmptyBuffer = ... a made-up type
ByteBuffer initialFullBuffer = ...
class FillingLoop implements Runnable {
public void run() {
ByteBuffer currentBuffer = initialEmptyBuffer;
try {
while (currentBuffer != null) {
addToBuffer(currentBuffer);
if (currentBuffer.remaining() == 0)
currentBuffer = exchanger.exchange(currentBuffer);
}
} catch (InterruptedException ex) { ... handle ... }
}
}
class EmptyingLoop implements Runnable {
public void run() {
ByteBuffer currentBuffer = initialFullBuffer;
try {
while (currentBuffer != null) {
takeFromBuffer(currentBuffer);
if (currentBuffer.remaining() == 0)
currentBuffer = exchanger.exchange(currentBuffer);
}
} catch (InterruptedException ex) { ... handle ...}
}
}
void start() {
new Thread(new FillingLoop()).start();
new Thread(new EmptyingLoop()).start();
}
}
No, it's no different from normal java variables or array elements.
Memory mapping with the JVM is just a thin wrapper around CreateFileMapping (Windows) or mmap (posix). As such, you have direct access to the buffer cache of the OS. This means that these buffers are what the OS considers the file to contain (and the OS will eventually synch the file to reflect this).
So there is no need to call force() to sync between processes. The processes are already synched (via the OS - even read/write accesses the same pages). Forcing just synchs between the OS and the drive controller (there can be some delay between the drive controller and the physical platters, but you don't have hardware support to do anything about that).
Regardless, memory mapped files are an accepted form of shared memory between threads and/or processes. The only difference between this shared memory and, say, a named block of virtual memory in Windows is the eventual synchronization to disk (in fact mmap does the virtual memory without a file thing by mapping /dev/null).
Reading writing memory from multiple processes/threads does still need some synch, as processors are able to do out-of-order execution (not sure how much this interacts with JVMs, but you can't make presumptions), but writing a byte from one thread will have the same guarantees as writing to any byte in the heap normally. Once you have written to it, every thread, and every process, will see the update (even through an open/read operation).
For more info, look up mmap in posix (or CreateFileMapping for Windows, which was built almost the same way.
No. The JVM memory model (JMM) does not guarantee that multiple threads mutating (unsynchronized) data will see each others changes.
First, given all the threads accessing the shared memory are all in the same JVM, the fact that this memory is being accessed through a mapped ByteBuffer is irrelevant (there is no implicit volatile or synchronization on memory accessed through a ByteBuffer), so the question is equivalent to one about accessing a byte array.
Let's rephrase the question so its about byte arrays:
- A manager has a byte array:
byte[] B_all
- A new reference to that array is created:
byte[] B_1 = B_all
, and given to threadT1
- Another reference to that array is created:
byte[] B_2 = B_all
, and given to threadT2
Do writes to
B_1
by threadT1
get seen inB_2
by threadT2
?
No, such writes are not guaranteed to be seen, without some explicit synchronization between T_1
and T_2
. The core of the problem is that the JVM's JIT, the processor, and the memory architecture are free to re-order some memory accesses (not just to piss you off, but to improve performance through caching). All these layers expect the software to be explicit (through locks, volatile or other explicit hints) about where synchronization is required, implying these layers are free to move stuff around when no such hints are provided.
Note that in practice whether you see the writes or not depends mostly on the hardware and the alignment of the data in the various levels of caches and registers, and how "far" away the running threads are in the memory hierarchy.
JSR-133 was an effort to precisely define the Java Memory Model circa Java 5.0 (and as far as I know its still applicable in 2012). That is where you want to look for definitive (though dense) answers: http://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf (section 2 is most relevant). More readable stuff can be found on the JMM web page: http://www.cs.umd.edu/~pugh/java/memoryModel/
Part of my answer is asserting that the a ByteBuffer
is no different from a byte[]
in terms of data synchronization. I can't find specific documentation that says this, but I suggest that "Thread Safety" section of the java.nio.Buffer doc would mention something about synchronization or volatile if that was applicable. Since the doc doesn't mention this, we should not expect such behavior.
One possible answer I've run across is using file locks to gain exclusive access to the portion of the disk mapped by the buffer. This is explained with an example here for instance.
I'm guessing that this would really guard the disk section to prevent concurrent writes on the same section of file. The same thing could be achieved (in a single JVM but invisible to other processes) with Java-based monitors for sections of the disk file. I'm guessing that would be faster with the downside of being invisible to external processes.
Of course, I'd like to avoid either file locking or page synchronization if consistency is guaranteed by the jvm/os.
I do not think that this is guaranteed. If the Java Memory Model doesn't say that it's guaranteed it is by definition not guaranteed. I would either guard buffer writes with synchronized or queue writes for one thread that handles all writes. The latter plays nicely with multicore caching (better to have 1 writer for each RAM location).