9

I'm encountering a recurrent issue in an application that tracks content of files within a directory, based on the Java 7 WatchService API. When the underlying file system fires a modification event on a file, I want to compute its SHA-256 right away.

But it often occurs that another process has the file opened (i.e. Word), thus detaining an exclusive lock and preventing my app from any read/write operation. If any Stream/Channel is created against the opened file, a FileNotFoundException or a FileSystemException for nio API's is thrown with a message like :

The process cannot access the file because it is being used by another process

I wasn't able to come with a solution that would detect such cases without masking a "real" FileNotFoundException when the file does not actually exists on the fs.

I've come up with the idea to check existence via File.exists and then if a FileNotFoundException is thrown when I open a stream I would be able to infer that the file is locked. I am open to any input on this!

Thanks!

ajduke
  • 4,991
  • 7
  • 36
  • 56
sylvain
  • 246
  • 2
  • 5

2 Answers2

1

Have you tried locking the file yourself? I would assume you can only acquire a lock if its not locked and exists.

http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#tryLock%28%29

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I was not able to call tryLock() since the mentioned exceptions are thrown when I attempt to get a FileChannel via RandomAccessFile or FileOutputStream. – sylvain Jan 10 '12 at 11:39
  • In that case it sounds like you have to check the Exception which is thrown when you attempt to access these files. I don't see the point of tryLock if you cannot call it if the file is locked. – Peter Lawrey Jan 10 '12 at 11:41
  • 1
    My guess is that native applications can have more restrictive locks than the ones available within the JVM. – sylvain Jan 10 '12 at 12:24
0

sharing documents accross processes is tricky especially when not using dedicated file systems (like GFS can be ).. I don't think that Java locking API may help you much, I think that you are on the right way with your idea of the try/fail strategy ... Using java 7 you could use a WatchService to monitor file changes and then acting as stated by your business requirements... What kind of system do you use ? Windows keeps handles on files during eternity...

HTH Jerome

romje
  • 650
  • 3
  • 4
  • Indeed I already have a WatchService thread listening for FS events, running only on Windows for the time being. Anyway I knew that there wouldn't be a way to access those locked files, but I am surprised there isn't an API within java.io or java.nio to test their accessibility. – sylvain Jan 10 '12 at 14:13