Concurrent file write in Java on Windows

前端 未结 4 2116
谎友^
谎友^ 2020-12-14 09:59

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

The Java API says this:

Some platforms, in particula

4条回答
  •  一生所求
    2020-12-14 10:07

    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.

提交回复
热议问题