The use of filelock in a multithreaded environment to achieve the lock function of the file, to avoid multiple threads simultaneously operating the same file,
Program:
public class demo{
Filelock lock;
/* Read/write file * *
Public Rwfile () {
Lock=trylock ();
if (lock!=null) {
Lock succeeded
You can work with the file.
Unlock ();
}else{
Lock failure
}
}
/* Lock operation return NON-EMPTY = Lock Success * *
Private Filelock Trylock () throws IOException {
File LOCKF = new file (root, "xxx.dat"); The file to lock
Lockf.deleteonexit (); Specifies that the lock is released when exiting
Randomaccessfile file = new Randomaccessfile (LOCKF, "RWS"); Specify the file to lock
Filelock res = null;
try {
res = File.getchannel (). Trylock (); Attempt to get a lock on the file
The catch (overlappingfilelockexception oe) {//file is thrown by another thread lock
File.close ();
return null;
catch (IOException e) {
Log.error ("Cannot create lock on" + LOCKF, E);
File.close ();
Throw e;
}
return res;
}
/* Unlock Operation * *
private void Unlock () throws IOException {
if (This.lock = null)
Return
This.lock.release ();
Lock.channel (). Close ();
lock = null;
}
}