File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes I/O and Streams and the fly likes File getting deleted on Mac System even though locked using FileChannel.lock() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "File getting deleted on Mac System even though locked using FileChannel.lock()" Watch "File getting deleted on Mac System even though locked using FileChannel.lock()" New topic
Author

File getting deleted on Mac System even though locked using FileChannel.lock()

Arpan Raj
Greenhorn

Joined: Apr 22, 2010
Posts: 15

Hi folks,
I have written a utility method to delete the file if its not currently being used by other threads (using simple IO).
To test it I have written the test case.

In which I will spawn a thread which will use FileChannel's lock or tryLock to obtain a lock and this thread goes to sleep. Other thread will try to delete the file.And I am expecting an exception as first thread as locked it and gone to sleep.
This scenario works fine on Windows but the same fails on Apple Mac.



I tried using other approach also like
In thread one : I will write in the file in the for loop and flush , and mean while thread 2 will try to delete the file. which again works on Windows but doesn't work on Mac.

I am not understanding why its deleting the file on Mac? When it should not delete and throw exception?
Any ideas? Work around? Reason?
Is it like Apple has not implemented file locking feature ?

Thanks in advance.
-Arpan
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2848
    
  11

It's an interesting question. I haven't worked a lot with channels and locking, but from the Javadocs:

File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.

So, you've got that working against you. Also, I believe Windows is more ... eager ... than Linux (and thus Mac OSX) in its interpretation of what locking should do, so that's probably why you're seeing different behavior on the different systems.
Arpan Raj
Greenhorn

Joined: Apr 22, 2010
Posts: 15

It looks like unix/Linux uses advisory and nothing prevents us from deleting a locked file.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: File getting deleted on Mac System even though locked using FileChannel.lock()