Premises:
I am trying to lock a file in a static function, the function returns a composed object that contains the channel and the lock so another function, unlockFile(FileLocking fl) can be used to close then channel and release the lock. The composed object class looks like this: `
public class FileLocking {
public FileChannel channel;
public FileLock lock;
public FileLocking(FileChannel f, FileLock l) {
channel = f;
lock = l;
}
The function that locks the file looks like this:
public static synchronized FileLocking lockFile(String fileName) {
FileLocking result = null;
FileChannel channel = null;
try {
channel = new FileOutputStream(fileName).getChannel();
FileLock lock = channel.lock();
lock = channel.tryLock();
result = new FileLocking(channel, lock);
} catch (Exception e) {
Log(ERR, "Exception when locking " + e.getMessage());
e.printStackTrace();
} finally {
try {
channel.close();
} catch (IOException e) {
Log(ERR, "IOE: " + e.getMessage());
e.printStackTrace();
}
}
return result;
}
Currently, i get the following error:
[ERR]: (pid:13) Exception when locking null
java.nio.channels.OverlappingFileLockException
at sun.nio.ch.FileChannelImpl$SharedFileLockTable.checkList(Unknown Source)
at sun.nio.ch.FileChannelImpl$SharedFileLockTable.add(Unknown Source)
at sun.nio.ch.FileChannelImpl.tryLock(Unknown Source)
at java.nio.channels.FileChannel.tryLock(Unknown Source)
at com.xxx.utils.FileLocking.lockFile(FileLocking.java:29)`
Explanations and/or coding techniques are highly appreciated.
Why do you call tryLock
after lock
again ? Am I missing something ?
You get OverlappingFileLockException since the lock is already held by the JVM, when you invoke tryLock
second time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With