Java文件锁定在网络上 [英] Java file locking on a network

查看:149
本文介绍了Java文件锁定在网络上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能与以前的帖子类似,但我想具体说明在网络上使用锁定,而不是在本地。我想将文件写入共享位置,因此它可能会进入网络(当然是Windows网络,也许是Mac)。我希望阻止其他人在撰写文件时阅读该文件的任何部分。这不是一个高度并发的过程,文件通常少于10MB。

This is perhaps similar to previous posts, but I want to be specific about the use of locking on a network, rather than locally. I want to write a file to a shared location, so it may well go on a network (certainly a Windows network, maybe Mac). I want to prevent other people from reading any part of this file whilst it it being written. This will not be a highly concurrent process, and the files will be typically less than 10MB.

我读过 FileLock 文档和文件文档,我有点困惑,关于什么是安全的,什么不是。我想锁定整个文件,而不是部分文件。

I've read the FileLock documentation and File documentation and am left somewhat confused, as to what is safe and what is not. I want to lock the entire file, rather than portions of it.

我可以使用 FileChannel.tryLock() ,它在网络上是安全的,还是取决于网络的类型?它是否适用于标准的Windows网络(如果有这样的话)。

Can I use FileChannel.tryLock(), and it is safe on a network, or does it depend on the type of network? Will it work on a standard Windows network (if there is such a thing).

如果这不起作用,最好将零字节文件或目录创建为锁定文件,然后写出主文件。为什么 File.createNewFile()文档说不要用它来进行文件锁定?我很欣赏这是受竞争条件限制的,并不理想。

If this does not work, is the best thing to create a zero byte file or directory as a lock file, and then write out the main file. Why does that File.createNewFile() documentation say don't use this for file locking? I appreciate this is subject to race conditions, and is not ideal.

推荐答案

这在网络文件上无法可靠地完成系统。只要您的应用程序是访问该文件的唯一应用程序,最好实现某种协作锁定过程(可能在打开文件时将锁定文件写入网络文件系统)。但是,不推荐的原因是,如果您的进程崩溃或网络出现故障或发生任何其他问题,您的应用程序将进入一个讨厌,肮脏的状态。

This can't be reliably done on a network file system. As long as your application is the only application that accesses the file, it's best to implement some kind of cooperative locking process (perhaps writing a lock file to the network filesystem when you open the file). The reason that is not recommended, however, is that if your process crashes or the network goes down or any other number of issues happen, your application gets into a nasty, dirty state.

这篇关于Java文件锁定在网络上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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