/**
* @param file
* @param strToWrite
* @param append
* @param lockTime 以毫秒为单位,该值只是方便模拟排他锁时使用,-1表示不考虑该字段
* @return
*/
public static boolean lockAndWrite(File file, String strToWrite, boolean append,int lockTime){
if(!file.exists()){
return false;
}
RandomAccessFile fis = null;
FileChannel fileChannel = null;
FileLock fl = null;
long tsBegin = System.currentTimeMillis();
try {
fis = new RandomAccessFile(file, "rw");
fileChannel = fis.getChannel();
fl = fileChannel.tryLock();
if(fl == null || !fl.isValid()){
return false;
}
log.info("threadId = {} lock success", Thread.currentThread());
// if append
if(append){
long length = fis.length();
fis.seek(length);
fis.writeUTF(strToWrite);
//if not, clear the content , then write
}else{
fis.setLength(0);
fis.writeUTF(strToWrite);
}
long tsEnd = System.currentTimeMillis();
long totalCost = (tsEnd - tsBegin);
if(totalCost < lockTime){
Thread.sleep(lockTime - totalCost);
}
} catch (Exception e) {
log.error("RandomAccessFile error",e);
return false;
}finally{
if(fl != null){
try {
fl.release();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fileChannel != null){
try {
fileChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public static void main(String[] args) {
new Thread("write-thread-1-lock"){
@Override
public void run() {
FileLockUtils.lockAndWrite(new File("/data/hello.txt"), "write-thread-1-lock" + System.currentTimeMillis(), false, 30 * 1000);}
}.start();
new Thread("write-thread-2-lock"){
@Override
public void run() {
FileLockUtils.lockAndWrite(new File("/data/hello.txt"), "write-thread-2-lock" + System.currentTimeMillis(), false, 30 * 1000);
}
}.start();
}
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.
public synchronized boolean obtain() throws IOException {
if (lock != null) {
// Our instance is already locked:
return false;
}
// Ensure that lockDir exists and is a directory.
if (!lockDir.exists()) {
if (!lockDir.mkdirs())
throw new IOException("Cannot create directory: " + lockDir.getAbsolutePath());
} else if (!lockDir.isDirectory()) {
// TODO: NoSuchDirectoryException instead?
throw new IOException("Found regular file where directory expected: " + lockDir.getAbsolutePath());
}
final String canonicalPath = path.getCanonicalPath();
// Make sure nobody else in-process has this lock held
// already, and, mark it held if not:
// This is a pretty crazy workaround for some documented
// but yet awkward JVM behavior:
//
// 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.
//
// This essentially means if we close "A" channel for a given file all
// locks might be released... the odd part
// is that we can't re-obtain the lock in the same JVM but from a
// different process if that happens. Nevertheless
// this is super trappy. See LUCENE-5738
boolean obtained = false;
if (LOCK_HELD.add(canonicalPath)) {
try {
channel = FileChannel.open(path.toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
try {
lock = channel.tryLock();
obtained = lock != null;
} catch (IOException | OverlappingFileLockException e) {
// At least on OS X, we will sometimes get an
// intermittent "Permission Denied" IOException,
// which seems to simply mean "you failed to get
// the lock". But other IOExceptions could be
// "permanent" (eg, locking is not supported via
// the filesystem). So, we record the failure
// reason here; the timeout obtain (usually the
// one calling us) will use this as "root cause"
// if it fails to get the lock.
failureReason = e;
}
} finally {
if (obtained == false) { // not successful - clear up and move
// out
clearLockHeld(path);
final FileChannel toClose = channel;
channel = null;
closeWhileHandlingException(toClose);
}
}
}
return obtained;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有