`

文件锁

阅读更多
public class FileLockTest {

public static void main(String[] args) throws Exception{

lock(); //文件锁-独占锁
lock(); //再次获取文件锁为空
}

static void lock()throws Exception{
File file = new File("D:\\lock");
RandomAccessFile lockFile = new RandomAccessFile(file, "rw");
FileLock lock = lockFile.getChannel().tryLock(0, 1, false);
if (lock == null || lock.isShared() || !lock.isValid()) {
            throw new RuntimeException("Lock failed");
        }

        lockFile.getChannel().write(ByteBuffer.wrap("lock3".getBytes()));
        lockFile.getChannel().force(true);
       
        /*if (lockFile != null && lock != null) {
            try {
                lock.release();
                lockFile.close();
            } catch (IOException e) {
            }
        }*/
}

}
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics