使用Java NIO 文件锁实现进程独占

代码来自HDFS DataNode中的使用方式…看起来相对容易,实际有几点需要注意,

1.文件一定要deleteOnExit().

2.发生异常一定要将RandoemAccessFile close()掉.

3.FileLock为null时要判断.

4.FileLock关闭时,先调用FileLock.release(), 而后FileLock.chanel().close();

public class FileLockDemo {
    private static final String FILE_LOCK_PATH = "c:" + File.separator;
    private static final String FILE_LOCK_FILE_NAME = "in_use.lock";

    private FileLock tryLock() throws IOException {
        File lockFile = new File(FILE_LOCK_PATH, FILE_LOCK_FILE_NAME);

        if(!lockFile.exists()) {
            lockFile.deleteOnExit();
        }

        RandomAccessFile file = new RandomAccessFile(lockFile, "rws");
        FileLock fileLock = null;
        try {
            fileLock = file.getChannel().tryLock();
            if(fileLock == null) {
                throw new OverlappingFileLockException();
            }
        } catch (OverlappingFileLockException e) {
            file.close();
            return null;
        }
        catch (IOException e) {
            file.close();
            throw e;
        }

        file.write(ManagementFactory.getRuntimeMXBean().getName().getBytes("UTF-8"));
        lockFile.deleteOnExit();
        return fileLock;
    }

    private void unLock(FileLock fileLock) throws IOException {
        if(fileLock == null) {
            return;
        }
        fileLock.release();
        fileLock.channel().close();
    }

    public static void main(String[] args) {
        for(int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileLockDemo demo = new FileLockDemo();
                        FileLock fileLock = demo.tryLock();
                        if(fileLock != null) {
                            System.out.println(String.format("%s get file lock...",
                                     Thread.currentThread().getName()));
                        }
                        else {
                            System.out.println(String.format("%s can not get file lock...",
                                    Thread.currentThread().getName()));
                        }
                        TimeUnit.SECONDS.sleep(30);
                        demo.unLock(fileLock);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }).start();
        }
    }
}

    原文作者:java锁
    原文地址: https://blog.csdn.net/u010666119/article/details/53455734
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞