When multiple threads work on a shared resource its quiet possible that one thread’s work is over written by another one if the shared resource is modified without a mutually exclusive lock. This can be solved by moving the code responsible for the state change of the shared resource into a synchronized method/block. What if the shared resource is outside the JVM? like a file and two program/process can change that file concurrently? In this kind of scenarios the file lock very useful. java.nio.channels package gives a class named FileLock to create a file lock in java, remember this implementation is platform dependent.
Let see a simple sample program to demonstrate the use of FileLock class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package com.ourownjava.corejava.file; import java.io.*; import java.nio.channels.*; /** * @date 1st May, 2011 * @author ourownjava.com * * To demonstrate the file lock API in java.nio * Example program for java file lock * */ public class FileLockExample { private FileLock lock(RandomAccessFile file) throws IOException{ final FileLock fileLock = file.getChannel().tryLock(); //if the JVM is not able to acquire a lock then a null //is returned, it could be because the lock is already acquired //by another thread or process. return fileLock; } public static void main(String args[]) throws IOException, InterruptedException{ final RandomAccessFile file = new RandomAccessFile(new File("/mnt/java/sample.file"), "rw"); final FileLockExample fthis = new FileLockExample(); final FileLock lock = fthis.lock(file); System.out.println("Got the lock? "+(null != lock)); if(null == lock){ return; } while(true){ if(null != lock){ System.out.println("Is a valid lock? "+lock.isValid()); } Thread.sleep(3000); } } } |
Execute the above program from two shell and see the result. The first jvm instance would get a lock but the second jvm instance would exit without a file lock.
Console Output.
1 2 3 4 5 6 7 8 9 |
/home/mnt/java com.ourownjava.corejava.file.FileLockExample Got the lock? true Is a valid lock? true Is a valid lock? true Is a valid lock? true Is a valid lock? true /home/mnt/java com.ourownjava.corejava.file.FileLockExample Got the lock? false |
Pingback: File lock in java. | Clean Java