I'm building a system in Java which has to copy a subset of a file into another file (not necessarily to the beginning of the file). I.e. I have the following parameters:
File srcFile, File dstFile, long srcFileOffset, long dstFileOffset, long length
Several threads could be reading from the same source-file and writing to the same destination-file (although with different offsets) simultaneosuly so I need the process to be thread-safe (i.e. preventing other threads from seeking in the file while a thread is writing/reading).
How would you implement this? Should I use a RandomAccessFile or Java NIO? What kind of locks do I need to acquire? E.g. does a RandomAccessFile-instance automatically acquire a system-wide lock on the file or do I need to keep that separately?
Edit: Looks like randomAccessFile.getChannel().tryLock()
acquires a system-wide lock but it's held by VM, not the calling thread. So if I'm using that then I need to acquire a lock for the thread as well (or two actually since I need to lock both the source- and destination-file).