Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's not a reliable, cross-platform way to be passively notified when a file has another writer&mdash;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.</p> <p>If multiple processes (which can be a mix of Java and non-Java) might be using the file, use a <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileLock.html" rel="nofollow noreferrer"><code>FileLock</code></a>. 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.</p> <p>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 href="https://stackoverflow.com/questions/659915/synchronizing-on-an-integer-value">a related question</a> can be adapted easily to do this with <code>File</code> objects or <a href="http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getCanonicalPath()" rel="nofollow noreferrer">canonical paths</a> to files. The lock object could be a <code>FileOutputStream</code>, some wrapper around the stream, or a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html" rel="nofollow noreferrer"><code>ReentrantReadWriteLock</code>.</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload