This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes locking a file from processing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "locking a file from processing" Watch "locking a file from processing" New topic
Author

locking a file from processing

Andrew Mcmurray
Ranch Hand

Joined: Sep 24, 2005
Posts: 188
Hi all

I have multiple processes monitoring the same directory for files to process. I want to be able to lock a file that is being processed so none of the other processes can start processing that file. I have seen methods that rename the file with '.' in front. Is this a good way to do it or is there a better way? Also when you rename do you create a new file?

Thanks,

AMD
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
I don't think there's anything special about renaming with a dot in front of the name, except that some platforms will hide that file from ordinary directory listings presented to the user. They will not be hidden from Java, I believe, even on those platforms.

However, if your programs "know" that a file starting with a dot is already being processed, then your idea ought to work, providing that renaming is "atomic", meaning no thread or process will see a part-renamed file.

Unfortunately, the Java API does not make any guarantees about how renaming (File.renameTo()) works. It might be atomic, or it might not.

In practice, I believe that renaming, within the same directory is atomic on Win/Lin/MacOSX. Therefore, your idea should work.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
... but a nicer architecture might be to have a single component responsible for scanning the directory. That component would then hand over responsibility for processing the files to one of a pool of processor components.
Andrew Mcmurray
Ranch Hand

Joined: Sep 24, 2005
Posts: 188
Thanks Peter,

So should I do something like this



Or can I just use file.rename on the original file?

Thanks,

AMD
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: locking a file from processing