How can I lock a file from within a Java application for all other processes on a operating system?

xetra11 :

I have a file I need to read several times from. I have to open the InputStream to the same file in sequence. Now I wonder if that file can be locked for the whole os as long as a specific portion of the Java application is running?

I want to prevent 3 from happening:

  1. Reading file example.txt from myApp.java
  2. Stop Reading file example.txt
  3. Other process writes file (i.e. echo "foo" >> example.txt)
  4. Reading file example.txt from myApp.java

As far as I understand java.nio.FileChannel lock does only lock access to a file for other JVM applications.

Slaw :

The Java API for this is java.nio.channels.FileLock. You say:

As far as I understand java.nio.FileChannel lock does only lock access to a file for other JVM applications.

That understanding is incorrect. From the documentation of FileLock:

Platform dependencies

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 [emphasis added].

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.

[...]

However, as you can see the exact nature of the lock is platform-specific.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194256&siteId=1