Strength and Buffering FileChannel #

I would like to make this clear and draw some parallels between FileOutputStream and FileChannel right now.

So, first of all, it seems that the most efficient way to write a file using standard Java io is to use FileOutputStream, which is wrapped by BufferedOutputStream . Because it is automatically flushed when the internal buffer is full. It is convenient to be able to make single entries (single bytes, floats, etc.), as well as massive ones and not worry about speed. The only thing you should never forget is to close it (execute the final flash). The benefits of using the BufferedOutputStream wrapper are obvious, and should have for everyone (hopefully).

Now about FileChannel. FileChannel has a force method that is equivalent to flush in FileOutputStream, right? And javadocs clearly say that you must use it to make sure your changes have been made to the target file. But I do not understand when and why to use it if there is no BufferedFileChannel shell. In other words, where is the buffering for the FileChannel? Is it automatic and hidden in the FileChannel file itself, as in BufferedOutputStream? If not, then why do I need a force method, because there is nothing forced (all changes are already applied to the file after using the write method), and I need to implement buffering myself?

+4
source share
1 answer

BufferedOutputStream have a cache in java that FileChannel does not.

However, FileChannel do have OS level cache. In which .force() matches fsync / fdatasync .

In OpenJDK 6 src/solaris/native/sun/nio/ch/FileChannelImpl.c

  157 JNIEXPORT jint JNICALL 158 Java_sun_nio_ch_FileChannelImpl_force0(JNIEnv *env, jobject this, 159 jobject fdo, jboolean md) 160 { 161 jint fd = fdval(env, fdo); 162 int result = 0; 163 164 if (md == JNI_FALSE) { 165 result = fdatasync(fd); 166 } else { 167 result = fsync(fd); 168 } 169 return handle(env, result, "Force failed"); 170 } 

Read this blog if you want to know more about how the OS works at this level.

+8
source

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


All Articles