Request the lock. If it is already locked this method will block until it become unblocked and the lock has been obtained.
165866
public void lock() {
		if (cancel != null)
			return;
		if (error != null)
			return;
		Thread t = Thread.currentThread();
		if (t == lockingThread) {
			lockedTimes++;
			return;
		}
		BlockedThreadHandler blockedHandler = null;
		do {
			synchronized (this) {
				if (lockingThread == null) {
					lockingThread = t;
					lockedTimes = 1;
					return;
				}
				if (blockedHandler == null)
					blockedHandler = Threading.getBlockedThreadHandler(t);
				if (blockedHandler == null) {
					try { this.wait(0); }
					catch (InterruptedException e) { /* ignore */ }
					continue;
				}
			}
			blockedHandler.blocked(this, 0);
		} while (true);
	}
801827
private synchronized boolean getServerLock() {

        Boolean fileExists = Boolean.FALSE;
        final File sDir = lockFile;
        try {
            fileExists = AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<Boolean>() {
                @Override
                public Boolean run() throws Exception {
                    if (!sDir.exists()) {
                        return Boolean.FALSE;
                    }
                    return Boolean.TRUE;
                }
            });
        } catch (Exception ex) {
            // Oh well.
        }
        if (!(fileExists.booleanValue()))
            return false;

        // Change to the "locking" state
        FileOutputStream fos = null;
        FileChannel fc = null;
        try {
            fos = new FileOutputStream(lockFile);
            fc = fos.getChannel();
            lockFileChannel = fc;

            // Try for a short period of time to obtain the lock
            // (if status mechanisms temporarily grab the file, we want to wait
            // to try to grab it.. )
            for (int i = 0; i < BootstrapConstants.MAX_POLL_ATTEMPTS; i++) {
                serverLock = fc.tryLock();
                if (serverLock != null) {
                    break;
                } else {
                    try {
                        Thread.sleep(BootstrapConstants.POLL_INTERVAL_MS);
                    } catch (InterruptedException e) {
                    }
                }
            }
        } catch (OverlappingFileLockException e) {
            // If we encounter an exception obtaining the lock, we can try
            // try closing the the relevant streams (channel first)
            if (!Utils.tryToClose(fc))
                Utils.tryToClose(fos);
        } catch (IOException e) {
            // If we encounter an exception obtaining the lock, we can try
            // try closing the the relevant streams (channel first)
            if (!Utils.tryToClose(fc)) // try to close the wrapping-channel first.
                Utils.tryToClose(fos);
        }

        return serverLock != null && serverLock.isValid();
    }
520015
public void lock(String key, String request) throws InterruptedException {
        //get connection
        Object connection = getConnection();
        String result ;
        for (; ;) {
            if (connection instanceof Jedis){
                result = ((Jedis)connection).set(lockPrefix + key, request, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, 10 * TIME);
                if (LOCK_MSG.equals(result)){
                    ((Jedis) connection).close();
                }
            }else {
                result = ((JedisCluster)connection).set(lockPrefix + key, request, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, 10 * TIME);
            }

            if (LOCK_MSG.equals(result)) {
                break;
            }

            Thread.sleep(sleepTime);
        }

    }
787841
public void queryLock (NodeObject.Lock lock, ResultListener<String> listener)
    {
        // if it's being resolved, add the listener to the list
        LockHandler handler = _locks.get(lock);
        if (handler != null) {
            handler.listeners.add(listener);
            return;
        }

        // otherwise, return its present value
        listener.requestCompleted(queryLock(lock));
    }
1007059
def get_lock (name, debug=False):
    
    lock = threading.Lock()
    # for thread debugging, use the DebugLock wrapper
    if debug:
        lock = DebugLock(lock, name)
    return lock
563580
private void lock(Object obtainer) throws PSQLException {
    if (lockedFor == obtainer) {
      throw new PSQLException(GT.tr("Tried to obtain lock while already holding it"),
          PSQLState.OBJECT_NOT_IN_STATE);

    }
    waitOnLock();
    lockedFor = obtainer;
  }
375405
void unlockProcessWait(ServerRequest.PROCESS_WAIT_LOCK lock) {
        synchronized (reqQueueLockObject) {
            for (ServerRequest req : queue) {
                if (req != null) {
                    req.removeProcessWaitLock(lock);
                }
            }
        }
    }
1166469
def lock!(*args)
      fail 'No block passed' unless block_given?

      lock(*args) do |lock_info|
        raise LockError, 'failed to acquire lock' unless lock_info
        return yield
      end
    end
1238888
def locked(self):
        
        conn = self._get_connection()
        try:
            self._lock(conn)
            yield conn
        finally:
            self._unlock(conn)
952695
def acquire(self, blocking=True):
        
        sleep = self.sleep
        timeout = self.timeout
        while 1:
            unixtime = time.time()
            if timeout:
                timeout_at = unixtime + timeout
            else:
                timeout_at = Lock.LOCK_FOREVER
            timeout_at = float(timeout_at)
            if self.redis.setnx(self.name, timeout_at):
                self.acquired_until = timeout_at
                return True
            # We want blocking, but didn't acquire the lock
            # check to see if the current lock is expired
            try:
                existing = float(self.redis.get(self.name) or 1)
            except ValueError:
                existing = Lock.LOCK_FOREVER

            if existing < unixtime:
                # the previous lock is expired, attempt to overwrite it
                try:
                    existing = float(self.redis.getset(self.name, timeout_at) or 1)
                except ValueError:
                    existing = Lock.LOCK_FOREVER
                if existing < unixtime:
                    # we successfully acquired the lock
                    self.acquired_until = timeout_at
                    return True
            if not blocking:
                return False
            time.sleep(sleep)
780989
def raise_or_lock(self, key, timeout):
        
        acquired = Lock(
            self.redis,
            key,
            timeout=timeout,
            blocking=self.blocking,
            blocking_timeout=self.blocking_timeout
        ).acquire()

        if not acquired:
            # Time remaining in milliseconds
            # https://redis.io/commands/pttl
            ttl = self.redis.pttl(key)
            raise AlreadyQueued(ttl / 1000.)
1066013
@Override public V get() {
    // check priorities - FJ task can only block on a task with higher priority!
    Thread cThr = Thread.currentThread();
    int priority = (cThr instanceof FJWThr) ? ((FJWThr)cThr)._priority : -1;
    assert _dt.priority() > priority || (_dt.priority() == priority && _dt instanceof MRTask)
      : "*** Attempting to block on task (" + _dt.getClass() + ") with equal or lower priority. Can lead to deadlock! " + _dt.priority() + " <=  " + priority;
    if( _done ) return result(); // Fast-path shortcut, or throw if exception
    // Use FJP ManagedBlock for this blocking-wait - so the FJP can spawn
    // another thread if needed.
    try { ForkJoinPool.managedBlock(this); } catch( InterruptedException ignore ) { }
    if( _done ) return result(); // Fast-path shortcut or throw if exception
    assert isCancelled();
    return null;
  }
955518
private void maybeSendNewPermitRequest() {
    if (!this.requestSemaphore.tryAcquire()) {
      return;
    }
    if (!this.retryStatus.canRetryNow()) {
      this.requestSemaphore.release();
      return;
    }
    try {
      long permits = computeNextPermitRequest();
      if (permits <= 0) {
        this.requestSemaphore.release();
        return;
      }

      PermitRequest permitRequest = this.basePermitRequest.copy();
      permitRequest.setPermits(permits);
      permitRequest.setMinPermits((long) this.permitsOutstanding.getAverageWeightOrZero());
      permitRequest.setVersion(ThrottlingProtocolVersion.WAIT_ON_CLIENT.ordinal());
      if (BatchedPermitsRequester.this.restRequestHistogram != null) {
        BatchedPermitsRequester.this.restRequestHistogram.update(permits);
      }

      log.debug("Sending permit request " + permitRequest);

      this.requestSender.sendRequest(permitRequest, new AllocationCallback(
          BatchedPermitsRequester.this.restRequestTimer == null ? NoopCloseable.INSTANCE :
              BatchedPermitsRequester.this.restRequestTimer.time(), new Sleeper()));
    } catch (CloneNotSupportedException cnse) {
      // This should never happen.
      this.requestSemaphore.release();
      throw new RuntimeException(cnse);
    }
  }
255559
def with_lock(lock, func, *args, **kwargs):
    
    d = lock.acquire()

    def release_lock(result):
        deferred = lock.release()
        return deferred.addCallback(lambda x: result)

    def lock_acquired(lock):
        return defer.maybeDeferred(func, *args, **kwargs).addBoth(release_lock)

    d.addCallback(lock_acquired)
    return d
1031804
def block(cls, method):
        
        def blocked_method(self, *a, **kw):
            raise cls(self, method.__name__, a, kw)
        return blocked_method
1114729
def acquire_lock(self):
    
    if self.options.for_global_scope().lock:
      if not self._lock.acquired:
        self._lock.acquire()
711847
public void acquireLock (final NodeObject.Lock lock, final ResultListener<String> listener)
    {
        // wait until any pending resolution is complete
        queryLock(lock, new ChainedResultListener<String, String>(listener) {
            public void requestCompleted (String result) {
                if (result == null) {
                    if (_suboids.isEmpty()) {
                        lockAcquired(lock, 0L, listener);
                    } else {
                        _locks.put(lock, new LockHandler(lock, true, listener));
                    }
                } else {
                    listener.requestCompleted(result);
                }
            }
        });
    }