I need to write lots of byte arrays sized from 1MB to 2MB to individual files. The data is always allocated as a byte[] (it is calculated) so I cannot use FileChannel.transferTo. After the write it should be guaranteed flushed to the disk.
Is this the fastest solution?
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, data.length);
buffer.put(data);
channel.force(false);
channel.close();
In my test-suite I see that the files sometimes are locked by the OS (or JVM) (java.io.File.delete() returns false) when I do a clean up. I'm concerned about the resources not getting released. People suggest using System.gc() and also some unsafe solutions, but maybe my program could hit a max limit? Should I be concerned? Will it be a problem allocating lots of memory mapped files? It is from the same thread so they will be closed before opening a new. Also my program must be able to delete these files.
Please also read How to unmap a file from memory mapped using FileChannel in java?