如何使用Java同步共享文件夹中的文件访问(或者:网络级别的ReadWriteLock) [英] Howto synchronize file access in a shared folder using Java (OR: ReadWriteLock on network level)

查看:188
本文介绍了如何使用Java同步共享文件夹中的文件访问(或者:网络级别的ReadWriteLock)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个虚拟机中运行多个应用程序。我在一台服务器上运行多个虚拟机。我有多台服务器。它们都使用linux上的共享文件夹共享文件。所有应用程序都会读取和写入该文件。在写入过程中,不允许任何应用程序读取此文件。编写相同:如果应用程序正在读取文件,则不允许应用程序编写它。

I have multiple applications running in one virtual machine. I have multiple virtual machines running on one server. And I have multiple servers. They all share a file using a shared folder on linux. The file is read and written by all applications. During the write process no application is allowed to read this file. The same for writing: If an application is reading the file no application is allowed to write it.

如何设置同步应用程序以便它们等待写入过程在读取之前完成,反之亦然? (必须同步vm中的应用程序以及服务器之间的应用程序)

Curent实现使用文件信号量。如果要写入文件,应用程序会尝试通过在共享文件夹中创建一个附加文件(将其命名为file.semaphore)来获取信号量。如果file.semaphore文件已存在,则表示信号量已被其他应用程序锁定。这种方法有问题,我无法确保文件存在-test和创建文件 - 操作是原子执行的。这样,两个应用程序可能会测试file.semaphore文件,看它不存在并尝试同时创建该文件。

Curent implementation uses "file semaphores". If the file is about to be written the application tries to "acquire" the semaphore by creating an additional file (lets name it "file.semaphore") in the shared folder. If the "file.semaphore" file already exists this means the semaphore is already locked by a different application. This approach has the problem that I cannot make sure that the "file exists"-test and "create file"- operation are executed atomic. This way it is possible that two applications test for the "file.semaphore" file, see it does not exist and try to create the file at the same time.

推荐答案

您可以使用NIO锁定功能。请参阅 FileChannel #lock()

You can use NIO locking capabilities. See FileChannel#lock().

但是,只有当底层文件系统支持锁定网络时,这才有效。最近的NFS应该支持它。也许,Samba也支持他们,但不能肯定地说。

However, this will work only if underlying filesystem supports locking over the network. Recent NFS should support it. Probably, Samba supports them too, but can’t say for sure.

参见文章

这篇关于如何使用Java同步共享文件夹中的文件访问(或者:网络级别的ReadWriteLock)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆