I wonder if someone could help me understand the behavior of Java FileLock.
I have one java program to lock the file:
And I have another program writing to the same file
When I run the first program in 2 java threads. The thread that started later would throw an exception, which is as expected, because file is already locked exclusively.
However, when I ran the second program immediately after the first program was started, the string was still written to the file, while the file was supposed to be locked exclusively.
Is it an expected behavior?
Is there any way in Java to acquire the file lock and prevent any application from writing into it?
Exception in thread "main" java.io.IOException: The process cannot access the file because another process has locked a portion of the file
at java.io.FileOutputStream.write(Native Method)
john sal wrote:Why java API does not contan these limitations?
Should they really contain?
It is already documented:
This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.
Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely advisory, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are mandatory, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks.