Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4676183

deleteOnExit should *not* be used for file-locking

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P3 P3
    • 1.4.1
    • 1.4.0
    • docs
    • beta
    • generic
    • generic

      The documentation for File.createNewFile say "This method, in combination with the deleteOnExit() method, can therefore serve as the basis for a simple but reliable cooperative file-locking protocol." This statement is false and dangerously misguided.

      If you mark the file as deleteOnExit *before* invoking createNewFile but the file already exists, you run the risk of deleting a file you didn't create and dropping someone elses lock! On the other hand, if you mark the file *after* creating it, you lose atomicity: if the program exits before the file is marked, it won't get deleted and the lock will be "wedged".

      Luckily, a proper file-locking facility was added in release 1.4 (java.nio.channels Class FileLock). The disinformative notation on File.createNewFile should be replaced by something like this:

      "Note: this method should <i>not</i> be used for file-locking, as the resulting protocol cannot be made to work reliably. The {@link java.nio.channels.FileLock FileLock} facility should be used instead."

      Perhaps this note should be added to the doc comment for File.deleteOnExit as well.

            shommel Scott Hommel (Inactive)
            jjb Josh Bloch
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: