在Windows上使用Java并发文件写入 [英] Concurrent file write in Java on Windows

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

问题描述

在同一文件上同时打开两个(或多个)FileOutputStream时会发生什么?



Java API 说明:


,特别是允许一次只打开一个FileOutputStream(或其他文件写入对象)的文件。


我猜Windows是不是这样的平台,因为我有两个线程读取一些大文件(每一个不同的一个),然后写入相同的输出文件。



其他问题:




  • 对于Unix也是这样吗?

  • 因为我想要的行为是一样的(实际上我想要一个线程正确写,



解决方案

没有可靠的跨平台方法可以在文件有另一个writer时被动通知,例如,如果文件已经打开可以写入,则抛出异常。但是,有几种技术可以帮助您主动检查这一点。



如果多个进程(可以是Java和非Java的混合)可能使用该文件,请使用 FileLock 。成功使用文件锁的一个关键是记住它们只是建议。锁保证是可见的,如果你检查它,但它不会阻止你做的事情,如果你忘记了文件。访问该文件的所有进程都应设计为使用锁定协议。



如果单个Java进程正在使用该文件,则可以使用Java中内置的并发工具做到安全。您需要一个映射对所有线程可见,将每个文件名与其相应的锁实例相关联。 相关问题的答案可以轻松修改为文件对象或规范路径到文件。锁对象可以是 FileOutputStream ,一些包装在流周围,或 ReentrantReadWriteLock


What happens when you concurrently open two (or more) FileOutputStreams on the same file?

The Java API says this:

Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time.

I'm guessing Windows isn't such a platform, because I have two threads that read some big file (each one a different one) then write it to the same output file. No exception is thrown, the file is created and seems to contain chunks from both input files.

Side questions:

  • Is this true for Unix, too?
  • And since I want the behaviour to be the same (actually I want one thread to write correctly and the other to be warned of the conflict), how can I determine that the file is already opened for writing?

解决方案

There's not a reliable, cross-platform way to be passively notified when a file has another writer—i.e., raise an exception if a file is already open for writing. There are a couple of techniques that help you actively check for this, however.

If multiple processes (which can be a mix of Java and non-Java) might be using the file, use a FileLock. A key to using file locks successfully is to remember that they are only "advisory". The lock is guaranteed to be visible if you check for it, but it won't stop you from doing things to the file if you forget. All processes that access the file should be designed to use the locking protocol.

If a single Java process is working with the file, you can use the concurrency tools built into Java to do it safely. You need a map visible to all threads that associates each file name with its corresponding lock instance. The answers to a related question can be adapted easily to do this with File objects or canonical paths to files. The lock object could be a FileOutputStream, some wrapper around the stream, or a ReentrantReadWriteLock.

这篇关于在Windows上使用Java并发文件写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
Java开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆