Java中的FileLock在Docker挂载卷中不起作用

时间:2020-07-22 07:53:51

标签: java docker filelock

在我的情况下,一些Web配置文件是通过Docker中的mount文件夹共享的。在相同情况下,我们要同时修改这些文件。这就是为什么我想使用锁来确保文件一次被修改。但是我发现flock在Docker中不起作用。不支持吗?

 public void modifyFile() {

    try {
        File file = new File("/tmp/fileToLock.dat");

        // Creates a random access file stream to read from, and optionally to write to
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        // Acquire an exclusive lock on this channel's file (blocks until lock can be retrieved)
        FileLock lock = null;

        // Attempts to acquire an exclusive lock on this channel's file (returns null or throws
        // an exception if the file is already locked.
        try {
            lock = channel.tryLock();
            if (null != lock) {
                List<String> fileToString = FileUtils.readLines(file, StandardCharsets.UTF_8);
                long l = 0l;
                if (null != fileToString && fileToString.size() > 0) {
                    l = Long.valueOf(fileToString.get(fileToString.size() - 1));
                }
                l++;
                FileUtils.writeStringToFile(file, String.valueOf(l) + "\r\n", StandardCharsets.UTF_8, true);
            }
        } catch (OverlappingFileLockException e) {
            // thrown when an attempt is made to acquire a lock on a a file that overlaps
            // a region already locked by the same JVM or when another thread is already
            // waiting to lock an overlapping region of the same file
            System.out.println("Overlapping File Lock Error: " + e.getMessage());
            channel.close();
        }

        // release the lock
        if (null != lock) {
            lock.release();
        }
        // close the channel
        channel.close();

    } catch (IOException e) {
        System.out.println("I/O Error: " + e.getMessage());
    }

}

1 个答案:

答案 0 :(得分:0)

最后,我只留下文件的任何锁实现,没有任何 Redis 锁的东西。

相关问题