Java I/O: Ensure a file is not locked by another process before any r/w operation
Asked Answered
T

2

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!

Thermo answered 10/1, 2012 at 11:21 Comment(2)
ever find a solution to this?Vanzandt
I ended up using the heuristic mentioned, if File.exists returns true within the FileNotFoundException catch block I interpret it as a file locked.Thermo
A
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

Alleyn answered 10/1, 2012 at 11:25 Comment(3)
I was not able to call tryLock() since the mentioned exceptions are thrown when I attempt to get a FileChannel via RandomAccessFile or FileOutputStream.Thermo
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.Alleyn
My guess is that native applications can have more restrictive locks than the ones available within the JVM.Thermo
T
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

Tautomer answered 10/1, 2012 at 12:16 Comment(1)
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.Thermo

© 2022 - 2024 — McMap. All rights reserved.