Read lock on file java
A token representing a lock on a region of a file. A file-lock object is created each time a lock is acquired on a file via one of the lock or tryLock methods of the FileChannel class, or the lock or tryLock methods of the AsynchronousFileChannel class. A file-lock object is initially valid. It remains valid until the lock is released by invoking the release method, by closing the channel that was used to acquire it, or by the termination of the Java virtual machine, whichever comes first. The validity of a lock may be tested by invoking its isValid method. A file lock is either exclusive or shared. A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Once it is released, a lock has no further effect on the locks that may be acquired by other programs. Whether a lock is exclusive or shared may be determined by invoking its isShared method. Some platforms do not support shared locks, in which case a request for a shared lock is automatically converted into a request for an exclusive lock. The locks held on a particular file by a single Java virtual machine do not overlap. The overlaps method may be used to test whether a candidate lock range overlaps an existing lock. A file-lock object records the file channel upon whose file the lock is held, the type and validity of the lock, and the position and size of the locked region. Only the validity of a lock is subject to change over time; all other aspects of a lock’s state are immutable. 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. File-lock objects are safe for use by multiple concurrent threads.
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. 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. On some systems, acquiring a mandatory lock on a region of a file prevents that region from being mapped into memory , and vice versa. Programs that combine locking and mapping should be prepared for this combination to fail. On some systems, closing a channel releases all locks held by the Java virtual machine on the underlying file regardless of whether the locks were acquired via that channel or via another channel open on the same file. It is strongly recommended that, within a program, a unique channel be used to acquire all locks on any given file. Some network filesystems permit file locking to be used with memory-mapped files only when the locked regions are page-aligned and a whole multiple of the underlying hardware’s page size. Some network filesystems do not implement file locks on regions that extend past a certain position, often 2 30 or 2 31 . In general, great care should be taken when locking files that reside on network filesystems.
Constructor Summary
Modifier | Constructor and Description |
---|---|
protected | FileLock (AsynchronousFileChannel channel, long position, long size, boolean shared) |
Method Summary
Lock mechanism using Files on Java
We have a process that can be executed from multiple places, even simultaneously, and a resource that is shared by said executions (it can be a file, a folder, a URL, a process, etc.).
We need to make sure that while this resource is being used, it is not modified, or that while we are modifying it, it is not used by other processes.
Let’s take as an example, we have a process that reads the content (files, folders) of a path and executes some logic. This process can be executed simultaneously 0 or more times. However, the content of this path can change from time to time: deleted files, added folders, or even modify the content of one or more files.
So we want to implement a locking mechanism that allows me exclusive use of the file for writing, and at the same time shared use while reading. We will do this using the Java NIO library.
Let’s do it
We will create a file, this can be located wherever you like, in this case we will place it in the root of the directory that we have as a resource. And we will call this file as .lock. We do not have to worry about the content of said file, we will only use the Java NIO options on this file to enable the locking mechanism.
Read LOCK
With the following code we can apply a Read Lock on a file:
Path lockFilePath = Paths.get("/my/path/.lock"); try (var channel = FileChannel.open(lockFilePath, StandardOpenOption.READ, StandardOpenOption.CREATE); FileLock lock = channel.lock(0, Long.MAX_VALUE, true)) < //Your logic here >
- We use the lock method of the FileChannel of our .lock file.
- The StandardOpenOption.READ option indicates that we are accessing in read mode, which allows other reading processes to also use the file simultaneously.
- The StandardOpenOption.CREATE option creates the .lock file for us if it does not exist (very first usage)
Write LOCK
With the following code we can apply a Write Lock on a file:
Path lockFilePath = Paths.get("/my/path/.lock"); try (var channel = FileChannel.open(lockFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE); FileLock lock = channel.lock(0, Long.MAX_VALUE, true)) < //Your logic here >
- We use the lock method of the FileChannel of our .lock file.
- The StandardOpenOption.WRITE option indicates that we are accessing in write mode, which does not allow other read or write processes to be accessing at the same time.
- The StandardOpenOption.CREATE option creates the .lock file for us if it does not exist (very first usage)
If for some reason we have a logic that is in write mode, and another reading or writing process tries to obtain a lock on the .lock file, that will not be possible. This process will wait until the initial writing process is finished, and only until that moment, it will continue.
Similarly, if there are one or more processes in read mode, and a writing process tries to lock the .lock file, this writing will wait until the reading processes finish .
Simplifying the code
Now that we understand the basics, we can create a class that helps us simplify that code, and make it more generic so that we can use it for multiple purposes.
public class < private final Path lockFilePath; public FileLockHelper(String path)< lockFilePath = Paths.get(path); >public T readLock(Executable function) throws IOException < try (var channel = FileChannel.open(lockFilePath, StandardOpenOption.READ, StandardOpenOption.CREATE); FileLock lock = channel.lock()) < return function.execute(); >> public T writeLock(Executable function) throws IOException < try (var channel = FileChannel.open(lockFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE); FileLock lock = channel.lock()) < return function.execute(); >> @FunctionalInterface public interface Executable < V execute() throws IOException; >>
We create a functional interface Executable to be used as a parameter in our methods, and then execute it as a lambda expression. In this way we can include any logic within the writeLock or readLock methods.
Finally, we can use the FileLockHelper this way.
FileLockHelper fileLockHelper = new FileLockHelper("/my/path/.lock"); fileLockHelper.writeLock(() -> < //Add my logic here return 1; >) fileLockHelper.read(() -> < //Add my logic here return "String"; >)
Conclusions
This mechanism can be used for multiple purposes, not just the exercise that was presented in this article. Ensuring the integrity of our data is very important, especially when we have applications that concurrently access the same resource.
Applying locking mechanisms is not an easy task, but with a little imagination you can find simple alternatives that can help us for many scenarios, like this one we have presented. Hoping it will be helpful to many people.
References
Read lock on file java
A token representing a lock on a region of a file. A file-lock object is created each time a lock is acquired on a file via one of the lock or tryLock methods of the FileChannel class, or the lock or tryLock methods of the AsynchronousFileChannel class. A file-lock object is initially valid. It remains valid until the lock is released by invoking the release method, by closing the channel that was used to acquire it, or by the termination of the Java virtual machine, whichever comes first. The validity of a lock may be tested by invoking its isValid method. A file lock is either exclusive or shared. A shared lock prevents other concurrently-running programs from acquiring an overlapping exclusive lock, but does allow them to acquire overlapping shared locks. An exclusive lock prevents other programs from acquiring an overlapping lock of either type. Once it is released, a lock has no further effect on the locks that may be acquired by other programs. Whether a lock is exclusive or shared may be determined by invoking its isShared method. Some platforms do not support shared locks, in which case a request for a shared lock is automatically converted into a request for an exclusive lock. The locks held on a particular file by a single Java virtual machine do not overlap. The overlaps method may be used to test whether a candidate lock range overlaps an existing lock. A file-lock object records the file channel upon whose file the lock is held, the type and validity of the lock, and the position and size of the locked region. Only the validity of a lock is subject to change over time; all other aspects of a lock’s state are immutable. 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. File-lock objects are safe for use by multiple concurrent threads.
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. 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. On some systems, acquiring a mandatory lock on a region of a file prevents that region from being mapped into memory , and vice versa. Programs that combine locking and mapping should be prepared for this combination to fail. On some systems, closing a channel releases all locks held by the Java virtual machine on the underlying file regardless of whether the locks were acquired via that channel or via another channel open on the same file. It is strongly recommended that, within a program, a unique channel be used to acquire all locks on any given file. Some network filesystems permit file locking to be used with memory-mapped files only when the locked regions are page-aligned and a whole multiple of the underlying hardware’s page size. Some network filesystems do not implement file locks on regions that extend past a certain position, often 2 30 or 2 31 . In general, great care should be taken when locking files that reside on network filesystems.