An implementation of the wait method which doesn't involve
        polling but instead utilizes a "real" synchronization
        scheme.
547134
def wait(self, timeout=None):
        
        import threading

        if self._state!=self.PENDING:
            return

        e = threading.Event()
        self.addCallback(lambda v: e.set())
        self.addErrback(lambda r: e.set())
        e.wait(timeout)
941480
def wait(self, seconds=None, **kw):
        ''
        # Use ping/pong to unblock recv for polling transport
        self._heartbeat_thread.hurry()
        # Use timeout to unblock recv for websocket transport
        self._transport.set_timeout(seconds=1)
        # Listen
        warning_screen = self._yield_warning_screen(seconds)
        for elapsed_time in warning_screen:
            if self._should_stop_waiting(**kw):
                break
            try:
                try:
                    self._process_packets()
                except TimeoutError:
                    pass
                except KeyboardInterrupt:
                    self._close()
                    raise
            except ConnectionError as e:
                self._opened = False
                try:
                    warning = Exception('[connection error] %s' % e)
                    warning_screen.throw(warning)
                except StopIteration:
                    self._warn(warning)
                try:
                    namespace = self.get_namespace()
                    namespace._find_packet_callback('disconnect')()
                except PacketError:
                    pass
        self._heartbeat_thread.relax()
        self._transport.set_timeout()
683219
@Override
    public void onKnownIssueAlreadySynchronized(final AcraReport pReport, final Issue pIssue)
            throws SynchronizationException {

        pReport.setStatus(SyncStatus.SUCCESS);
    }
596298
void waitForReady() {
    if (!ready) {
      writeLock();
      try {
        while (!ready) {
          try {
            cond.await(5000, TimeUnit.MILLISECONDS);
          } catch (InterruptedException ie) {
          }
        }
      } finally {
        writeUnlock();
      }
    }
  }
541984
public void async() {
		final Request request = data.build();
		final CallbackHandler handler = request.handler != null ? request.handler : singleton.handler;
		final boolean safe = request.safe != null ? request.safe : singleton.safe;

		// Ignore current request if already running (ignoreIfRunning)
		synchronized (activeRequests) {
			if (ignoreIfRunning && activeRequests.contains(request.tag)) {
				singleton.log(request.tag + " request already running! Ignoring...");
				return;
			}
			activeRequests.add(request.tag);
		}

		new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				try {
					// Delay thread if specified
					if (delay > 0) {
						singleton.log("Delaying " + request.tag + " request for " + delay + "ms");
						Thread.sleep(delay);
					}

					// Execute request
					try {
						singleton.load(request);
					} catch (IOException e) {
						singleton.log("Error executing request " + request.tag + " asynchronously! " + e.getMessage(), Log.ERROR);
						handler.onLoadFailed(safe, request.callback.get());
					}
				} catch (InterruptedException e) {
					singleton.log(request.tag + " thread interrupted!");
				} finally {
					synchronized (activeRequests) {
						activeRequests.remove(request.tag);
					}
				}
				return null;
			}

			@Override
			protected void onCancelled(Void aVoid) {
				super.onCancelled(aVoid);

				// Double check to make sure this request is removed
				synchronized (activeRequests) {
					activeRequests.remove(request.tag);
				}
			}
		}.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
	}
291880
public void waitTillAllUpdatesExecuted() throws InterruptedException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "waitTillAllUpdatesExecuted");
    synchronized (this)
    {
      while (enqueuedUnits.size() > 0 || executing)
      {
        try
        {
          this.wait();
        }
        catch (InterruptedException e)
        {
          // No FFDC code needed
          if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "waitTillAllUpdatesExecuted", e);
          throw e;
        }
      }
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "waitTillAllUpdatesExecuted");
  }
337977
private synchronized static void waiting(String classname, int fnr,
			int offset)
	{
		m.put(classname, StaticOperationsCounters.waiting[fnr] += offset);
		stateChanged();
	}
729992
@Override
    public IPromise<T> awaitPromise(long timeout) {
        long endtime = 0;
        if ( timeout > 0 ) {
            endtime = System.currentTimeMillis() + timeout;
        }
        if ( Thread.currentThread() instanceof DispatcherThread ) {
            DispatcherThread dt = (DispatcherThread) Thread.currentThread();
            Scheduler scheduler = dt.getScheduler();
            int idleCount = 0;
            dt.__stack.add(this);
            while( ! isSettled() ) {
                if ( ! dt.pollQs() ) {
                    idleCount++;
                    scheduler.pollDelay(idleCount);
                } else {
                    idleCount = 0;
                }
                if ( endtime != 0 && System.currentTimeMillis() > endtime && ! isSettled() ) {
                    timedOut(Timeout.INSTANCE);
                    break;
                }
            }
            dt.__stack.remove(dt.__stack.size()-1);
            return this;
        } else {
            // if outside of actor machinery, just block
            CountDownLatch latch = new CountDownLatch(1);
            then( (res, err) -> {
                latch.countDown();
            });
            boolean timedOut = false;
            try {
                timedOut = ! latch.await(timeout, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if ( timedOut )
                timedOut(Timeout.INSTANCE);
            return this;
        }
    }
164434
synchronized void sync()
    {
        try
        {
            // check we have more work to do
            if (allocatePosition.get() <= lastSyncedOffset + SYNC_MARKER_SIZE)
                return;

            // allocate a new sync marker; this is both necessary in itself, but also serves to demarcate
            // the point at which we can safely consider records to have been completely written to
            int nextMarker;
            nextMarker = allocate(SYNC_MARKER_SIZE);
            boolean close = false;
            if (nextMarker < 0)
            {
                // ensure no more of this CLS is writeable, and mark ourselves for closing
                discardUnusedTail();
                close = true;

                // wait for modifications guards both discardedTailFrom, and any outstanding appends
                waitForModifications();

                if (discardedTailFrom < buffer.capacity() - SYNC_MARKER_SIZE)
                {
                    // if there's room in the discard section to write an empty header, use that as the nextMarker
                    nextMarker = discardedTailFrom;
                }
                else
                {
                    // not enough space left in the buffer, so mark the next sync marker as the EOF position
                    nextMarker = buffer.capacity();
                }
            }
            else
            {
                waitForModifications();
            }

            assert nextMarker > lastSyncedOffset;

            // write previous sync marker to point to next sync marker
            // we don't chain the crcs here to ensure this method is idempotent if it fails
            int offset = lastSyncedOffset;
            final PureJavaCrc32 crc = new PureJavaCrc32();
            crc.updateInt((int) (id & 0xFFFFFFFFL));
            crc.updateInt((int) (id >>> 32));
            crc.updateInt(offset);
            buffer.putInt(offset, nextMarker);
            buffer.putInt(offset + 4, crc.getCrc());

            // zero out the next sync marker so replayer can cleanly exit
            if (nextMarker < buffer.capacity())
            {
                buffer.putInt(nextMarker, 0);
                buffer.putInt(nextMarker + 4, 0);
            }

            // actually perform the sync and signal those waiting for it
            buffer.force();

            if (close)
                nextMarker = buffer.capacity();

            lastSyncedOffset = nextMarker;
            syncComplete.signalAll();

            CLibrary.trySkipCache(fd, offset, nextMarker);
            if (close)
                internalClose();
        }
        catch (Exception e) // MappedByteBuffer.force() does not declare IOException but can actually throw it
        {
            throw new FSWriteError(e, getPath());
        }
    }
539000
private IGPSObject waitForResult() {
		synchronized (this.asyncWaitMutex) {
			if (this.asyncResult == null) {
				try {
					this.asyncWaitMutex.wait(1000);
				} catch (final InterruptedException e) {
					GPSdEndpoint.LOG.info("Interrupted while waiting for result", e);
				}
			}
			final IGPSObject result = this.asyncResult;
			this.asyncResult = null;
			return result;
		}
	}
551444
public WaitQueue.Signal requestExtraSync()
    {
        WaitQueue.Signal signal = syncComplete.register();
        haveWork.release(1);
        return signal;
    }
1229740
def asynchronous(method):
    
    def _async(*args, **kwargs):
        GObject.idle_add(method, *args, **kwargs)
    return _async
1311356
def call_sync(func):
    """"""

    @wraps(func)
    def wrapper(self, *args, **kw):
        """Wraps instance method to be called on loop thread"""

        # Just return when already on the event thread
        if self.thread.ident == get_ident():
            return func(self, *args, **kw)

        barrier = Barrier(2)
        result = None
        ex = None

        def call():
            """Calls function on loop thread"""
            nonlocal result, ex
            try:
                result = func(self, *args, **kw)
            except Exception as exc:
                ex = exc
            finally:
                barrier.wait()

        self.loop.call_soon_threadsafe(call)
        barrier.wait()
        if ex:
            raise ex or Exception("Unknown error")
        return result

    return wrapper
1200191
def _wait(self, generator, method, timeout=None, *args, **kwargs):
        """"""
        if self.debug:
            print("waiting for %s to pause" % generator)

        original_timeout = timeout
        while timeout is None or timeout > 0:
            last_time = time.time()
            if self._lock.acquire(False):  # timeout param was added in 3.2
                try:
                    if self.can_resume():
                        return method(generator, *args, **kwargs)
                    elif self.has_terminated():
                        raise RuntimeError("%s has already terminated" % generator)
                finally:
                    self._lock.release()

            if timeout is not None:
                timeout -= time.time() - last_time

        msg = "%s did not pause after %ss" % (generator, original_timeout)
        if self.debug:
            print(msg)
        raise WaitTimeoutError(msg)
949123
public static void waitForDie(Thread thread) {
		boolean dead = false;
		do {
			try {
				thread.join();
				dead = true;
			} catch (InterruptedException e) {
				// ignore
			}
		} while (!dead);
	}
412300
@Override
    public V poll(long timeout, TimeUnit unit) throws InterruptedException {
        return blockingQueue.poll(timeout, unit);
    }
1070290
public void randomWait(long min, long max) {
		final long waitTime = randomLong(min, max);
		try {
			Thread.sleep(waitTime);
		} catch (InterruptedException interruptedException) {
			// ignored
		}
	}