OverlappingFileLockException when trying to lock a file channel

Service premises:

  • I get an OverlappingFileLockException every time I try to lock a file (this applies to all files)
  • I have a machine just loaded.
  • Tested on Windows / Linux via Eclipse, java v1.6
  • Only one instance of Eclipse works with this single program.
  • Only one thread running in this program (event sending thread)
  • I tried to lock files that I had never touched before
  • Same issue using both lock () and trylock ()
  • Switching from FileOutputStream () to RandomAccessFile () gives the same result

I am trying to lock a file in a static function, the function returns a compound object that contains the channel and the lock, so another function, unlockFile (FileLocking fl) can be used to close the channel and release the lock. The complex object class is as follows: `

public class FileLocking { public FileChannel channel; public FileLock lock; public FileLocking(FileChannel f, FileLock l) { channel = f; lock = l; } 

The file lock function is as follows:

 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; 

}

I am currently getting 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)` 

The concepts and / or coding methods are highly appreciated.

+4
source share
1 answer

Why are you calling tryLock again after lock ? Did I miss something?

You get an OverlappingFileLockException since the lock is already held by the JVM when you call tryLock second time.

+6
source

Source: https://habr.com/ru/post/1396406/


All Articles