Question

I have 2 applications running in parallel, both doing the following:

  • check for file not containing "processed"
  • process the file and then rename it to filename+processed
  • for every file, only one application shall use it (on a first come first served basis)

I get the files and I also lock them so the other application cannot process it. But when it comes to renaming the file I get a problem. To rename the file, wanted to use the File.renameTo function. However, for that to work, I have to release the lock on the file. But when I release the lock another process may try to use the file. Exactly that should not happen.

Is there any way to prevent the application B from using the file between application A releasing the lock and finishing renaming the file?

EDIT

Some more information:

  • File creation if the file doesn't exist has to be prevented.
  • The file will be processed RandomAccessFile (with read and write permission; this creates a new file if it doesn't exist).

Note: On linux, one can rename a file that is locked, so this problem doesn't occur there. However, on Windows a locked file cannot be renamed; I have to release the lock, then rename it. But the time, during which the lock is released creates enables other applications to see that the file is available and then they will try to use it.

Was it helpful?

Solution

Windows applications can do this using the SetFileInformationByHandle function, which allows you to rename the file using the handle you already have open. You probably can't do this natively from Java.

However, a more straightforward solution would be to rename the file (to filename+processing, for example) before you start processing it. Whichever process successfully renames the file in this way is the one responsible for processing it and eventually renaming it to filename+processed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top