For Java MMAp, modifying MappedByteBuffer is equivalent to modifying the file. The operating system then flushed the disk through the PDflush process according to the algorithm of the priority search tree. Even if our program dies, the operating system will flush dirty pages from this portion of memory to disk. However, if the system hangs, restarts, etc., this part of the data will be lost.
Do we have a way to force a disk flush? The system call for Linux is the msync() function (see: man7.org/linux/man-p… Mappedbytebuffer.force (), but using this method can greatly reduce efficiency, use with caution!
MappedByteBuffer.java:
public final MappedByteBuffer force() { checkMapped(); if ((address ! = 0) && (capacity() ! = 0)) { long offset = mappingOffset(); Force0 force0(fd, mappingAddress(offset), mappingLength(offset)); } return this; }Copy the code
MappedByteBuffer.c:
JNIEXPORT void JNICALL Java_java_nio_MappedByteBuffer_force0(JNIEnv *env, jobject obj, jobject fdo, jlong address, jlong len) { void* a = (void *)jlong_to_ptr(address); // call msync int result = msync(a, (size_t)len, MS_SYNC); if (result == -1) { JNU_ThrowIOExceptionWithLastError(env, "msync failed"); }}Copy the code
Wechat search “my programming meow” public account, a daily brush, easy to improve skills, won a variety of offers