Filelock is a file lock, process lock, for inter-process concurrency, which controls concurrent access by different programs (JVMS) to the same file.
Filelock is a Java 1.4 version of a class, it can be a writable file (W) lock, to ensure that only one process can get the file lock, the process so that the file can be accessed, and the other cannot get the lock process or choose to be suspended waiting, Or choose to do something else, a mechanism that ensures that the process can access the file sequentially.
As can be seen, the ability to take advantage of this nature of file locks, in some scenarios, although we do not need to manipulate a file, but also through the filelock to carry out concurrency control, to ensure the sequential execution of the process, to avoid data errors.
Java. NiO. Channels. FileChannel,filechannel is a class in NiO.
Exclusive Lock : Also known as exclusive lock, if one thread obtains an exclusive lock on a file, other threads cannot obtain an exclusive or shared lock on the same file until the exclusive lock is freed.
Shared Locks : If a thread acquires a shared lock on a file, other threads can obtain a shared lock on the same file or a shared lock of the same file part, but cannot get an exclusive lock
When the A.txt file is exclusive, other threads are unreadable and not writable.
Other threads are readable and not writable when the A.txt file is added to a shared lock.
Fc.trylock (Position,size,isshare); The third argument is true when a shared lock.
Lock () Blocking method, the locking range can increase as the file grows.
Trylock () non-blocking, returns NULL when no lock is obtained.
Filelock life cycle: Call Filelock.release () or channel.close (), or the JVM shuts down.
Boolean java.nio.channels.FileLock.overlaps (long position, long size), true indicates that the current lock is within the range, false indicates that the current lock's area does not overlap the parameter area.
The effect of a file lock is related to the operating system. File locks are mandatory in some systems (mandatory), and when a Java process obtains a file lock, the operating system guarantees that other processes will not be able to do the file exercises. While other operating system file lock is inquiry (advisory), meaning to have the effect of mutex process, other processes must also follow the API as stipulated in the application or detection of file locks, otherwise, will not be the process of mutual exclusion function. For example, on a Linux platform, different processes can read and write a file at the same time, need to request or detect file locks.
Therefore, it is recommended that all systems be treated as a query system, which is more secure and easier to migrate.
Lock when reading and writing critical data, unlock when operation is complete,lock. Release(); Put it in the finally.
Apply for all required resources at one time and discard the requested resources in case of unsuccessful application;
Public classFilelocktest {/*** As shown in the code, a process that needs to be mutually exclusive can simply replace//mutex with its own code, * each process will attempt to acquire a lock file lock before running the actual logic function code, * The process that gets the file lock will continue to execute the subsequent code, and the process that does not get the lock file is System hangs (suspend), * Wait until other processes release the file lock and try to get the file lock again. * In this way, the process can be implemented through Filelock to achieve mutually exclusive operation. * @paramargs*/ Public Static voidMain (string[] args) {FileChannel channel=NULL; Filelock Lock=NULL; Try {//Nonwritablechannelexception exception is reported when a read-only file is locked in any way//nonreadablechannelexception exceptions are also reported when the write channel is locked by means of a lock () .//no parameter lock () defaults to exclusive locks and does not report nonreadablechannelexception exceptions, because exclusive is to write//the so-called share can only read shared, write is exclusive, shared lock control code can only be read operation//channel = new FileOutputStream ("LogFile.txt", True). Getchannel ();Randomaccessfile RAF=NewRandomaccessfile ("LogFile.txt", "RW"); Raf.seek (Raf.length ());//RAF handling of appending content at the end of a fileChannel=Raf.getchannel (); //get the Lock method a lock, blocking method, when the file lock is not available, the current process will be suspended//lock = Channel.lock (0L, Long.max_value, true);//shared lock, write operation will report an exceptionLock= Channel.lock ();//Exclusive Lock//get the Lock method two Trylock, non-blocking method, Trylock () will get a null value when the file lock is not available//Do {//lock = Channel.trylock ();//} while (null = = lock);//Mutex OperationBytebuffer Sendbuffer=bytebuffer.wrap ((NewDate () + "Write \ n"). GetBytes ()); Channel.write (Sendbuffer); Thread.Sleep (5000); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } Catch(interruptedexception e) {e.printstacktrace (); } finally { if(Lock! =NULL) { Try{lock.release (); Lock=NULL; } Catch(IOException e) {e.printstacktrace (); } } if(Channel! =NULL) { Try{channel.close (); Channel=NULL; } Catch(IOException e) {e.printstacktrace (); } } } }}/*** Interval two times a second run the program, the program will be under the control of the file lock to logfile.txt mutually exclusive operation LogFile.txt content: Thu 15:39:02 CST 2012 Write Thu 16 1 5:39:07 CST 2012 Write the following exception is reported when the second method is used, if the file lock is not yet obtained: Exception in thread "main" Java.io.IOException: Another program is locked The process cannot be accessed as part of the file. At Sun.nio.ch.FileDispatcher.write0 (Native Method) at Sun.nio.ch.FileDispatcher.write (Unknown Source) at sun.nio.ch. Ioutil.writefromnativebuffer (Unknown source) at Sun.nio.ch.IOUtil.write (Unknown source) at SUN.NIO.CH.FILECHANNELIMP L.write (Unknown Source) at Filelocktest.main (filelocktest.java:19)*/
File Lock Filelock