code: 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;
      }
    }
docs: Get a lock on file if not already locked
  
  @param fs
  @param dir  the dir on which to get a lock
  @return The lock object if it the lock was acquired. Returns null if the dir is already locked.
  @throws IOException if there were errors