code: public static FileLock lockRandomAccessFile(final RandomAccessFile file, final int tryLockMax, final long tryWaitMillis)
              throws LockingFailedException {
  
          checkNotNull("file", file);
  
          final FileChannel channel = file.getChannel();
  
          int tryCount = 0;
          while (tryCount < tryLockMax) {
              tryCount++;
              try {
                  final FileLock lock = channel.tryLock();
                  if (lock != null) {
                      return lock;
                  }
              } catch (final IOException ex) {
                  throw new LockingFailedException("Unexpected I/O-Exception!", ex);
              } catch (final OverlappingFileLockException ex) {
                  ignore();
              }
              try {
                  Thread.sleep(tryWaitMillis);
              } catch (final InterruptedException ex) { // NOSONAR
                  throw new LockingFailedException("Unexpected interrupt!", ex);
              }
          }
          throw new LockingFailedException("Number of max tries (" + tryLockMax + ") exceeded!");
  
      }
docs: Lock the file.
  
  @param file
  File to lock - Cannot be <code>null</code>.
  @param tryLockMax
  Number of tries to lock before throwing an exception.
  @param tryWaitMillis
  Milliseconds to sleep between retries.
  
  @return FileLock.
  
  @throws LockingFailedException
  Locking the file failed.