4

I am using Java NIO in spring batch application. The application looks in a directory (e.g. /shared/inbox) where /shared is network shared disk among all instances of applications running on different JVMs.

To avoid multiple threads reading same files, in my ItemReader I take a FileLock and avoid other threads to read from it.

While I am done reading, I want to move the file to another directory (e.g. /shared/archive). But the Files.move method cannot do that unless I give up the FileLocl, and if I give up the lock, I run the risk of some other thread picking the file.

Question is, can I move the file from inbox to archive without giving up the FileLock?

  • Well evidently not. Using a shared folder won't help. – user207421 Jan 29 '16 at 21:01
  • Can't you just copy the file, put a lock on the new file then release the old lock? – Chris Gerken Jan 29 '16 at 21:32
  • 1
    I ended up solving the problem by creating another tmp file to indicate other threads of my application that the file is already picked up by a thread. Then I release the lock and move the file. Not elegant, but it does the job for now. – Overly Optimized Feb 04 '16 at 16:44
  • @OverlyOptimized thanks for sharing your solution man. I'm also facing the same problem. Please let me know if you came up with a better solution. – Arshad Yusuf Dec 01 '22 at 17:20

1 Answers1

0

Try to copy the file using java.nio.channels.FileChannel

private static void copyFileUsingFileChannels(File source, File dest)throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();

        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}

Good luck

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
ZIMIL
  • 9
  • 1