FileChannel Class tryLock() Method in Java with Examples
In the case of a multi-threaded program, where multiple threads are in execution concurrently, we require locks to be acquired and released to maintain synchronization among the processes. FileChannel Class of java also provides a method known as trylock() which is used to acquire a lock on the File specified. This method is used to acquire a lock on any region of the file, specified in the parameters of the method.
A lock may be a more flexible and complicated thread synchronization mechanism than the standard synchronized block. A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. However, some locks may allow concurrent access to a shared resource, like the read lock of a ReadWriteLock.
Here the output is the object of FileLock class which mentions the lock applied, if no lock is applied (maybe due to the reason that some other processes are holding or writing the file) then this method will return null. The Position variable specifies the mark of the file from where the lock is to be acquired and the extent (up to which the lock is to be acquired) is given by the ‘size’ variable. If nothing is mentioned in the place of the second parameter then the size of Long.MAX_VALUE is taken by default. The “shared” boolean variable tells that whether the lock is shared or not. If it is false then the lock is an exclusive one otherwise shared among other processes. These are some basics of the method of synchronization. Its default value is taken to be false.
The main advantage of this method is that it will never be blocked. After the invocation, it either returns the acquired lock or returns null if the file is handled by another process or raises an exception. This method is generally different from the lock() method of the same class in the sense that in synchronization process had to wait long to get access to file or resources and acquire locks, but this method will never wait in turn it will return the null or exception.
Syntax: Method declaration
public abstract FileLock tryLock(long position, long size, boolean shared) throws IOException
We are creating two threads that will try to access the file and perform a write operation on it. since to maintain synchronization we are using the trylock() method. When one of the threads acquires a lock and is doing an operation on the file and then if a second thread calls the lock to be acquired then an exception is raised by the method as the file is not free to be acquired. In the above code, we had acquired lock explicitly on the whole file. If desired we can change the size of the portion of the file on which the lock has to be acquired.
Please Login to comment...