Java Reference
In-Depth Information
This method will attempt to acquire an exclusive lock on the channel's file so that no other program or
thread can access the file while this channel holds the lock. If another program or thread already has a
lock on the file, the
lock()
method will block until the lock on the file is released and can be acquired
by this channel. The lock that is acquired is owned by the channel,
ioChannel
, and will be
automatically released when the channel is closed. By saving the reference to the
FileLock
object, we
can release the lock on the file when we are done by calling the
release()
method for the
FileLock
object. This invalidates the lock so file access is no longer restricted. You can call the
isValid()
method for a
FileLock
object to determine whether it is valid. A return value of true indicates a valid
lock, otherwise false will be returned. Note that once created, a
FileLock
object is immutable. It also
has no further effect on file access once it has been invalidated. If you want to lock the file a second
time you must acquire a new lock.
Having your program hang until a lock is acquired is not an ideal situation. It is quite possible a file
could be locked permanently - at least until the computer is rebooted - because of a programming error
in another program, in which case your program will hang indefinitely. The
tryLock()
method for a
channel offers an alternative way of requesting a lock that does not block. It either returns a reference to
a valid
FileLock
object or returns
null
if the lock could not be acquired. This gives your program a
chance to do something else or retire gracefully:
FileLock ioFileLock = null;
try {
ioFileLock = ioChannel.tryLock();
if(ioFileLock == null) {
System.out.println("The file's locked - again!! Oh, I give up...");
System.exit(1);
}
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
We will see in an example a better response to a lock than this, but you get the idea.
Locking Part of a File
There are overloaded versions of the
lock()
and
tryLock()
methods that allow you to specify just a
part of the file you want to obtain a lock on:
Requests a lock on the region of this channel's file starting at
position
and of
length
size. If the last argument is
true
,
the lock requested is a
shared lock
. If it is
false
the lock
requested is an
exclusive lock
. If the lock cannot be obtained for
any reason, the method will block until the lock can be obtained
or the channel is closed by another thread.
lock(long position,
long size,
boolean shared)
This works in the same way as the method above, except that
null
will be returned if the requested lock cannot be acquired.
This avoids the potential for hanging your program indefinitely.
tryLock(long position,
long size,
boolean shared)