Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OverlappingFileLockException when trying to lock a file channel

Tags:

java

locking

Premises:

  • I get OverlappingFileLockException every time i try to lock a file (this applies to all files)
  • I have a freshly booted machine
  • Tested on both Windows/Linux through Eclipse, java v1.6
  • Just one instance of Eclipse is running with this single program
  • Just one thread running in this program (event dispatching thread)
  • I have tried to lock files that i have never touched before
  • Same problem using both lock() and trylock()
  • Changing from FileOutputStream() to RandomAccessFile() yields same result

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.

like image 226
ola1olsson Avatar asked Feb 14 '12 13:02

ola1olsson


1 Answers

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.

like image 139
Anton Avatar answered Nov 15 '22 23:11

Anton