Enable Lock of files (default is not enabled), call before use {@link #open()}
763803
public void enableLocking() {
		if (validState) {
			throw new InvalidStateException();
		}
		if (Boolean.getBoolean(Constants.PROP_IO_LOCKING)) {
			useLock = false;
			log.info("Disabled Locking in System Property (" + Constants.PROP_IO_LOCKING + ")");
		} else {
			useLock = true;
			log.info("Enabled Locking");
		}
	}
231444
boolean tryLock(Path lockFile) throws JobLockException {
    log.debug("Attempting lock: {}", lockFile);
    try {
      return this.fs.createNewFile(lockFile);
    } catch (IOException e) {
      throw new JobLockException(e);
    }
  }
651853
public void openImageSet(String ...files ) {
		synchronized (lockStartingProcess) {
			if( startingProcess ) {
				System.out.println("Ignoring open image set request.  Detected spamming");
				return;
			}
			startingProcess = true;
		}

		stopAllInputProcessing();

		synchronized (inputStreams) {
			inputMethod = InputMethod.IMAGE_SET;
			inputFileSet = files;
			if( threadProcess != null )
				throw new RuntimeException("There is still an active stream thread!");
			threadProcess = new ProcessImageSetThread(files);
			imageSetSize = files.length;
		}
		threadPool.execute(threadProcess);
	}
646644
public void lock() throws IOException {
    for (int i = 0; i < LOCK_MAX_RETRIES; ++i) {
      try {
        fileLock = channel.tryLock(0, 1, false);
        break;
      } catch (OverlappingFileLockException e) {
        OLogManager.instance().debug(this,
            "Cannot open file '" + osFile.getAbsolutePath() + "' because it is locked. Waiting %d ms and retrying %d/%d...",
            LOCK_WAIT_TIME, i, LOCK_MAX_RETRIES);

        // FORCE FINALIZATION TO COLLECT ALL THE PENDING BUFFERS
        OMemoryWatchDog.freeMemory(LOCK_WAIT_TIME);
      }
    }

    if (fileLock == null)
      throw new OLockException(
          "File '"
              + osFile.getPath()
              + "' is locked by another process, maybe the database is in use by another process. Use the remote mode with a OrientDB server to allow multiple access to the same database.");
  }
701961
public boolean lock() throws Exception {
        synchronized (this) {
            if (fileLock != null) {
                throw new Exception("The lock is already held");
            }
            if (log.isDebugEnabled()) {
                log.debug("Acquiring lock on " + lockFile.getAbsolutePath());
            }
            try {
                fileChannel = new RandomAccessFile(lockFile, "rw").getChannel();
                fileLock = fileChannel.tryLock();
            } catch (OverlappingFileLockException | IOException e) {
                throw new Exception("Exception occurred while trying to get a lock on file: " +
                        lockFile.getAbsolutePath(), e);
            }
            if (fileLock == null) {
                if (fileChannel != null) {
                    try {
                        fileChannel.close();
                    } catch (IOException ie) {
                        // ignore
                    }
                    fileChannel = null;
                }
                return false;
            } else {
                return true;
            }
        }
    }
831450
def lock_file(path, maxdelay=.1, lock_cls=LockFile, timeout=10.0):
    
    lock = lock_cls(path)
    max_t = time.time() + timeout
    while True:
        if time.time() >= max_t:
            raise LockTimeout("Timeout waiting to acquire lock for %s" % (path,))  # same exception messages as in lockfile
        try:
            lock.acquire(timeout=0)
        except AlreadyLocked:
            sleep(maxdelay)
        else:
            try:
                yield lock
                break
            finally:
                lock.release()
171369
private function releaseWhenLockIsPresentAndTimeDeltaAllows()
    {
        $fileInfo = $this->getFileInfo();
        $lockIsPresent = $fileInfo->isFile();

        if ($lockIsPresent) {
            $this->releaseWhenTimeDeltaAllows();
        }
    }
1307936
def _simple_lock(f):
    
    lock_file = f + ".lock"
    timeout = 20
    curtime = 0
    interval = 2
    while os.path.exists(lock_file):
        time.sleep(interval)
        curtime += interval
        if curtime > timeout:
            os.remove(lock_file)
    with open(lock_file, "w") as out_handle:
        out_handle.write("locked")
    yield
    if os.path.exists(lock_file):
        os.remove(lock_file)
22282
public static DirLock tryLock(FileSystem fs, Path dir) throws IOException {
    Path lockFile = getDirLockFile(dir);

    try {
      FSDataOutputStream ostream = HdfsUtils.tryCreateFile(fs, lockFile);
      if (ostream!=null) {
        LOG.debug("Thread ({}) Acquired lock on dir {}", threadInfo(), dir);
        ostream.close();
        return new DirLock(fs, lockFile);
      } else {
        LOG.debug("Thread ({}) cannot lock dir {} as its already locked.", threadInfo(), dir);
        return null;
      }
    } catch (IOException e) {
        LOG.error("Error when acquiring lock on dir " + dir, e);
        throw e;
    }
  }
320878
private void disableWithoutCheck() throws IOException {
        // creates an empty file
        try (OutputStream os = Files.newOutputStream(disableFile.toPath())) {
            os.close();
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }
    }
54013
public static FileLocker getLock(File lockFile) {
        lockFile.getParentFile().mkdirs();
        if (!lockFile.exists()) {
            try {
                IOHelper.write(lockFile, "I have the lock!");
                lockFile.deleteOnExit();
                return new FileLocker(lockFile);
            } catch (IOException e) {
                // Ignore
            }
        }
        return null;

    }
902256
public void lockBlocks(long fileId, List<Long> blockIds) throws IOException {
    Map<Long, Long> blockIdToLockId = new HashMap<>();
    List<Throwable> errors = new ArrayList<>();
    synchronized (mLock) {
      if (mPersistingInProgressFiles.containsKey(fileId)) {
        throw new IOException("the file " + fileId + " is already being persisted");
      }
    }
    try {
      // lock all the blocks to prevent any eviction
      for (long blockId : blockIds) {
        long lockId = mBlockWorker.lockBlock(Sessions.CHECKPOINT_SESSION_ID, blockId);
        blockIdToLockId.put(blockId, lockId);
      }
    } catch (BlockDoesNotExistException e) {
      errors.add(e);
      // make sure all the locks are released
      for (long lockId : blockIdToLockId.values()) {
        try {
          mBlockWorker.unlockBlock(lockId);
        } catch (BlockDoesNotExistException bdnee) {
          errors.add(bdnee);
        }
      }

      if (!errors.isEmpty()) {
        StringBuilder errorStr = new StringBuilder();
        errorStr.append("failed to lock all blocks of file ").append(fileId).append("\n");
        for (Throwable error : errors) {
          errorStr.append(error).append('\n');
        }
        throw new IOException(errorStr.toString());
      }
    }
    synchronized (mLock) {
      mPersistingInProgressFiles.put(fileId, blockIdToLockId);
    }
  }
168329
def lock_file(path):
    
    with _paths_lock:
        lock = _paths_to_locks.get(path)
        if lock is None:
            _paths_to_locks[path] = lock = _FileLock(path)
    return lock
1211651
@Override
    public File getFileWithDefault(String key, String file) {
        String value = get(key);
        if (value == null) {
            return new File(baseDirectory, file);
        } else {
            return new File(baseDirectory, value);
        }
    }
407889
public FileLock lock(final long iRangeFrom, final long iRangeSize, final boolean iShared) throws IOException {
    return channel.lock(iRangeFrom, iRangeSize, iShared);
  }
914196
public function lock()
    {
        if (!$this->isLocked()) {
            $file = fopen($this->getFilePath(), 'w');
            if ($file) {
                fwrite($file, getmypid());
                fclose($file);
                return true;
            }
        }
        return false;
    }
1201530
private void ensureIndexIsUnlocked(String dataDir) {

        Collection<File> lockFiles = new ArrayList<File>(2);
        lockFiles.add(
            new File(
                CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + "index") + "write.lock"));
        lockFiles.add(
            new File(
                CmsFileUtil.addTrailingSeparator(CmsFileUtil.addTrailingSeparator(dataDir) + "spellcheck")
                    + "write.lock"));
        for (File lockFile : lockFiles) {
            if (lockFile.exists()) {
                lockFile.delete();
                LOG.warn(
                    "Forcely unlocking index with data dir \""
                        + dataDir
                        + "\" by removing file \""
                        + lockFile.getAbsolutePath()
                        + "\".");
            }
        }
    }