Creating a File Lock on a File
The behavior of the file lock is platform-dependent. On some
platforms, the file lock is advisory, which means that unless an
application checks for a file lock, it will not be prevented from
accessing the file. On other platforms, the file lock is mandatory,
which means that a file lock prevents any application from accessing
the file.
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
// Release the lock
lock.release();
// Close the file
channel.close();
} catch (Exception e) {
}
channel.tryLock() does not throw an exception, but returns null if the lock is already busy.
Thank you for the correction, Patrik.
Jeez. You have to love all these people who post examples when they don't know what they're doing, googling for answers is a minefield of bad advice. Bad depot farmer! No ad click cookie for you!
Actually tryLock() can throw an exception if the file is already locked in the same JVM (very likely to happen in an application server).
So, Patrick and Leonard are wrong and, besides, Leonard was unnecessarily rude ( I love all these people who comment...).
I want to ask a question. When the lock is held, if jvm is terminated abnormally (for example kill -9), how is the lock released? Thanks
very naic
very nice
i would like to use this software.
This site is like a caslsroom, except I don't hate it. lol
Instead of using channel.close(), try lock.channel.close(). It would be a good option while accessing inside static methods.
Instead of using channel.close(), try lock.channel.close(). It would be a good option while accessing inside static methods.
any body can help me to make a code example of file lock for java.?and show the output.
thank you.
how to save of code to file