示例#1
0
 /**
  * Performs locking. If returns {@code true}, locking was successful and caller holds the lock.
  * Multiple invocations, after lock is acquired, does not have any effect, locking happens only
  * once.
  */
 public synchronized boolean lock() {
   if (fileLock != null) {
     return true;
   }
   try {
     randomAccessFile = new RandomAccessFile(lockFile, "rws");
     fileLock = randomAccessFile.getChannel().tryLock(0L, 1L, false);
     if (fileLock != null) {
       randomAccessFile.setLength(0);
       randomAccessFile.seek(0);
       randomAccessFile.write(payload);
     }
   } catch (IOException | OverlappingFileLockException e) {
     // handle it as null result
     fileLock = null;
   } finally {
     if (fileLock == null) {
       release();
       return false;
     }
   }
   return true;
 }