OK, 8.5 years is a long time, but I hope it is not necro ...
My problem was that we needed to access the threads in order to read and write as atomic as possible. The important part was that our code had to work on several computers accessing the same file. However, all the examples on the Internet settled on explaining how to block RandomAccessFile , and did not go deeper. So my starting point was Sam's answer .
Now, from a distance it makes sense to have a certain order:
- lock file
- open streams
- do with threads
- close streams
- release the lock
However, to release the lock in Java, threads should not be closed! Because of this, the whole mechanism becomes a bit strange (and wrong?).
To perform an automatic close, remember that the JVM closes objects in the reverse order of the try segment. This means the stream is as follows:
- open streams
- lock file
- do with threads
- release the lock
- close streams
Tests have shown that this will not work. Therefore, automatically close halfway and do the rest in a good "Java 1" style:
try (RandomAccessFile raf = new RandomAccessFile(filename, "rwd"); FileChannel channel = raf.getChannel()) { FileLock lock = channel.lock(); FileInputStream in = new FileInputStream(raf.getFD()); FileOutputStream out = new FileOutputStream(raf.getFD());
Note that methods using this must be synchronized . Otherwise, parallel executions can raise an OverlappingFileLockException when calling lock() .
Share your experience if you have ...
source share