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 ?
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.