Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

locking a file from processing

 
Andrew Mcmurray
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... 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
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Peter,

So should I do something like this



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

Thanks,

AMD
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic