Locking Files
In addition to enabling high-performance I/O, the FileChannel
class also enables file locking, a feature that is not
available through the java.io
package. Example 6-1
demonstrates how it can be used to prevent two instances of the same
application from running at the same time. When the program starts, it
attempts to obtain an exclusive write lock on a temporary file. If it
succeeds, it just sleeps for 10 seconds to simulate a real
application. If it fails, it prints a message saying that another
instance of the application is running.
The example also demonstrates simple write and read operations
on the file using a ByteBuffer
. If the program obtains a write lock on the file, it writes a timestamp 10 seconds in the future into the file (this is the approximate time when the program will stop sleeping and exit). If the program does not obtain a lock on the file, it attempts to read the file anyway. If the underlying operating system enforces locking, this read attempt will fail because another instance of the application holds the lock. Many operating systems, however, provide only advisory locking in which all applications must cooperatively use file-locking calls in order to prevent concurrent access. On an operating system, or Java implementation that performs only advisory locking, the program will be allowed to read the file contents even if another instance of the program has an exclusive lock. In this case, the application reads the timestamp written by the ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.