0

I have a program that locks a file like so, where lock is the file:

FileChannel channel = new RandomAccessFile(lock,"rw").getChannel();
FileLock lock = channel.lock();

The main purpose is, using a secondary program, check to see if the program was killed. The secondary program's code looks like this:

boolean isNotLocked = false;
while (true){
   while (isNotLocked){
       lock.renameTo(lock);
   }
//run the program again
}

It works the first time, and the program is run again, but after the program is run again, the secondary program throws a OverlappingFileLockException and terminates. The main program is creating the lock, not the secondary one.

user2352923
  • 47
  • 1
  • 9
  • You cannot lock the same file more than once simultaneously.Try to create `lock.deleteOnExit();` with "rwd". And check with secondary program is `lockFile.exists()`. If not you can create another one. – newuserua_ext Nov 11 '16 at 12:46
  • It has the same effect. I'm not trying to detect if the user closes it via the exit button or using Alt+F4, I'm trying to detect if its process is killed, by Task Manager or other sources. – user2352923 Nov 11 '16 at 12:52
  • So you may use Runtime.getRuntime().addShutdownHook() . Here is the example https://www.tutorialspoint.com/java/lang/runtime_addshutdownhook.htm – newuserua_ext Nov 11 '16 at 12:56
  • It doesn't seem to be triggering, am I doing something wrong here? I'm creating the class just like in the example (with a different name) and I'm calling it like this: `Runtime.getRuntime().addShutdownHook(new releaseLock());` – user2352923 Nov 11 '16 at 13:18
  • Hmm, Java file locks are POSIX advisory locks, which should be removed when the program exits. http://stackoverflow.com/questions/23562369/is-a-java-filelock-a-posix-advisory-fcntl-lock – Raedwald Nov 11 '16 at 18:53
  • @user2352923 Did you solve your problem? If not lets show what you have tried – newuserua_ext Nov 14 '16 at 05:37

0 Answers0