e182. creating a shared file lock on a file.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 32 行

TXT
32
字号
By default, a file lock is exclusive, which means that once acquired, no other access is permitted. A shared file lock allows other shared locks on the file (but no exclusive locks). 
Note: Some platforms do not support shared locks, in which case the lock is automatically made into an exclusive lock. Use FileLock.isShared() to determine the type of the lock. 

    try {
        // Obtain a file channel
        File file = new File("filename");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    
        // Create a shared lock on the file.
        // This method blocks until it can retrieve the lock.
        FileLock lock = channel.lock(0, Long.MAX_VALUE, true);
    
        // Try acquiring a shared lock without blocking. This method returns
        // null or throws an exception if the file is already exclusively locked.
        try {
            lock = channel.tryLock(0, Long.MAX_VALUE, true);
        } catch (OverlappingFileLockException e) {
            // File is already locked in this thread or virtual machine
        }
    
        // Determine the type of the lock
        boolean isShared = lock.isShared();
    
        // Release the lock
        lock.release();
    
        // Close the file
        channel.close();
    } catch (Exception e) {
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?