java - Java 中的 FileLock 在 Docker 挂载卷中不起作用
问题描述
在我的情况下,一些 Web 配置文件是通过 Docker 中的挂载文件夹共享的。在相同的情况下,我们希望同时修改这些文件。这就是为什么我想使用 lock 来确保文件同时被修改一次。但我发现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());
}
}
解决方案
最后,我只为文件保留任何锁实现,而没有任何 Redis 锁。
推荐阅读
- android - 中心可组合在屏幕的中心
- amazon-web-services - 高效删除 Elasticsearch 中的旧文档
- amazon-web-services - 在 aws wafv2 上执行标记操作时 ARN 无效
- anylogic - 时间分布和在任何逻辑中花费的时间
- python - SWIG,将 python 列表传递给 C++
- javascript - Google Apps 脚本 - 根据参考表循环更新多个命名范围
- react-native - Babel 不会使用插件
- pyspark - PySpark 缺少列名错误,Azure Synapse 分析笔记本中的数字列名
- android - 从另一个片段Android Kotlin返回时如何不调用函数
- flutter - 在颤动中保存所有选项卡的数据