Submits a ticket to flush thread and waits until ticket is served.

If the specified counter is already flushed, this is essentially a no-op.

@param targetCounter the counter to flush
427350
public void flush(final long targetCounter) throws IOException, JournalClosedException {
    // Return if flushed.
    if (targetCounter <= mFlushCounter.get()) {
      return;
    }

    // Submit the ticket for flush thread to process.
    FlushTicket ticket = new FlushTicket(targetCounter);
    try (LockResource lr = new LockResource(mTicketLock)) {
      mTicketList.add(ticket);
    }

    try {
      // Give a permit for flush thread to run.
      mFlushSemaphore.release();

      // Wait on the ticket until completed.
      ticket.waitCompleted();
    } catch (InterruptedException ie) {
      // Interpret interruption as cancellation.
      throw new AlluxioStatusException(Status.CANCELLED.withCause(ie));
    } catch (Throwable e) {
      // Filter, journal specific exception codes.
      if (e instanceof IOException) {
        throw (IOException) e;
      }
      if (e instanceof JournalClosedException) {
        throw (JournalClosedException) e;
      }
      // Not expected. throw internal error.
      throw new AlluxioStatusException(Status.INTERNAL.withCause(e));
    } finally {
      /**
       * Client can only try to reacquire the permit it has given
       * because the permit may or may not have been used by the flush thread.
       */
      mFlushSemaphore.tryAcquire();
    }
  }
724275
@Override
  public void flush() {
    try {
      out.flush();
    }
    catch(Exception ex) {
      reportError(null, ex, ErrorManager.FLUSH_FAILURE);
    }
    try {
      err.flush();
    }
    catch(Exception ex) {
      reportError(null, ex, ErrorManager.FLUSH_FAILURE);
    }
  }
391076
public void failUnacknowledgedPendingCheckpointsFor(ExecutionAttemptID executionAttemptId, Throwable cause) {
		synchronized (lock) {
			Iterator<PendingCheckpoint> pendingCheckpointIterator = pendingCheckpoints.values().iterator();

			while (pendingCheckpointIterator.hasNext()) {
				final PendingCheckpoint pendingCheckpoint = pendingCheckpointIterator.next();

				if (!pendingCheckpoint.isAcknowledgedBy(executionAttemptId)) {
					pendingCheckpointIterator.remove();
					discardCheckpoint(pendingCheckpoint, cause);
				}
			}
		}
	}
901065
private CompletableFuture<Void> flush(Void ignored) {
        checkRunning();
        long traceId = LoggerHelpers.traceEnterWithContext(log, this.traceObjectId, "flush");

        // Flush everything we can flush.
        val flushFutures = this.processors.values().stream()
                                          .filter(ProcessorCollection::mustFlush)
                                          .map(a -> a.flush(this.config.getFlushTimeout()))
                                          .collect(Collectors.toList());

        return Futures
                .allOfWithResults(flushFutures)
                .thenAcceptAsync(flushResults -> {
                    FlushStageResult result = new FlushStageResult();
                    flushResults.forEach(result::withFlushResult);
                    if (result.getFlushedBytes() + result.getMergedBytes() + result.count > 0) {
                        logStageEvent("Flush", result);
                    }

                    LoggerHelpers.traceLeave(log, this.traceObjectId, "flush", traceId);
                }, this.executor);
    }
1280163
def flush(self, queue_name):
        
        for _ in iter_queue(self.queues[queue_name]):
            self.queues[queue_name].task_done()
567521
public void flush() throws InterruptedException {
    List<Entry> toFlush = new ArrayList<>(mEvictBatchSize);
    Iterator<Entry> it = mMap.values().iterator();
    while (it.hasNext()) {
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }
      while (toFlush.size() < mEvictBatchSize && it.hasNext()) {
        Entry candidate = it.next();
        if (candidate.mDirty) {
          toFlush.add(candidate);
        }
      }
      flushEntries(toFlush);
      toFlush.clear();
    }
  }
157461
private void onAttemptComplete(Throwable t) {
        try {
            if (circuitBreaker != null) {
                if (t instanceof CircuitBreakerOpenException) {
                    metricRecorder.incrementCircuitBreakerCallsCircuitOpenCount();
                } else if (circuitBreaker.isFailure(null, t)) {
                    metricRecorder.incrementCircuitBreakerCallsFailureCount();
                } else {
                    metricRecorder.incrementCircuitBreakerCallsSuccessCount();
                }
            }

            if (t instanceof TimeoutException) {
                metricRecorder.incrementTimeoutTrueCount();
            } else {
                metricRecorder.incrementTimeoutFalseCount();
            }
        } catch (RuntimeException e) {
            // Unchecked exceptions thrown here can be swallowed by Failsafe
            // This catch ensures we at least get an FFDC
            throw e;
        }
    }
1217717
private void flushUpdateQueue() {
        LOG.debug("Run flushUpdateQueue.");

        final int size = queue.size();
        if (size <= 0) {
            return;
        }

        LOG.debug("{} events in flushUpdateQueue.", size);

        final Set<TargetPoll> events = Sets.newHashSetWithExpectedSize(queue.size());
        final int drained = queue.drainTo(events);

        if (drained <= 0) {
            return;
        }

        try {
            events.stream().collect(Collectors.groupingBy(TargetPoll::getTenant)).forEach((tenant, polls) -> {
                final TransactionCallback<Void> createTransaction = status -> updateLastTargetQueries(tenant, polls);
                tenantAware.runAsTenant(tenant,
                        () -> DeploymentHelper.runInNewTransaction(txManager, "flushUpdateQueue", createTransaction));
            });
        } catch (final RuntimeException ex) {
            LOG.error("Failed to persist UpdateQueue content.", ex);
            return;
        }

        LOG.debug("{} events persisted.", drained);
    }
257694
public synchronized void release(int count) {
        used -= count;
        if (used < 0)
            used = 0; // no negative number of ticket!
        if (logger.isDebugEnabled())
            logger.debug("Released " + count + " tickets! (Now " + this.toString() + ")");
        notifyAll();
    }
627375
private void flush() {

        if (pendingAbsoluteValueBug != null) {
            absoluteValueAccumulator.accumulateBug(pendingAbsoluteValueBug, pendingAbsoluteValueBugSourceLine);
            pendingAbsoluteValueBug = null;
            pendingAbsoluteValueBugSourceLine = null;
        }
        accumulator.reportAccumulatedBugs();
        if (sawLoadOfMinValue) {
            absoluteValueAccumulator.clearBugs();
        } else {
            absoluteValueAccumulator.reportAccumulatedBugs();
        }
        if (gcInvocationBugReport != null && !sawCurrentTimeMillis) {
            // Make sure the GC invocation is not in an exception handler
            // for OutOfMemoryError.
            boolean outOfMemoryHandler = false;
            for (CodeException handler : exceptionTable) {
                if (gcInvocationPC < handler.getHandlerPC() || gcInvocationPC > handler.getHandlerPC() + OOM_CATCH_LEN) {
                    continue;
                }
                int catchTypeIndex = handler.getCatchType();
                if (catchTypeIndex > 0) {
                    ConstantPool cp = getThisClass().getConstantPool();
                    Constant constant = cp.getConstant(catchTypeIndex);
                    if (constant instanceof ConstantClass) {
                        String exClassName = (String) ((ConstantClass) constant).getConstantValue(cp);
                        if ("java/lang/OutOfMemoryError".equals(exClassName)) {
                            outOfMemoryHandler = true;
                            break;
                        }
                    }
                }
            }

            if (!outOfMemoryHandler) {
                bugReporter.reportBug(gcInvocationBugReport);
            }
        }

        sawCurrentTimeMillis = false;
        gcInvocationBugReport = null;

        exceptionTable = null;
    }
469472
private void onSuspend(final List<Address> members) {
        Message msg = null;
        Collection<Address> participantsInFlush = null;
      synchronized (sharedLock) {
         flushCoordinator = localAddress;         

         // start FLUSH only on group members that we need to flush
         participantsInFlush = members;
         participantsInFlush.retainAll(currentView.getMembers());
         flushMembers.clear();
         flushMembers.addAll(participantsInFlush);
         flushMembers.removeAll(suspected);
         
          msg = new Message(null).src(localAddress).setBuffer(marshal(participantsInFlush, null))
            .putHeader(this.id, new FlushHeader(FlushHeader.START_FLUSH, currentViewId()));

      }
        if (participantsInFlush.isEmpty()) {
            flush_promise.setResult(SUCCESS_START_FLUSH);
        } else {
            down_prot.down(msg);
            if (log.isDebugEnabled())
                log.debug(localAddress + ": flush coordinator "
                        + " is starting FLUSH with participants " + participantsInFlush);
        }
    }
463553
@Override
	public void notifyTimeout(AllocationID key, UUID ticket) {
		checkInit();

		if (slotActions != null) {
			slotActions.timeoutSlot(key, ticket);
		}
	}
1187402
private void flush(FlinkKafkaProducer.KafkaTransactionState transaction) throws FlinkKafkaException {
		if (transaction.producer != null) {
			transaction.producer.flush();
		}
		long pendingRecordsCount = pendingRecords.get();
		if (pendingRecordsCount != 0) {
			throw new IllegalStateException("Pending record count must be zero at this point: " + pendingRecordsCount);
		}

		// if the flushed requests has errors, we should propagate it also and fail the checkpoint
		checkErroneous();
	}
138263
def put(self, target, callback = None, name = None, *args, **kargs):
        
        self.count_lock.acquire()
        if not self.shared['workers']:
            self.add(name = name)
        self.count_lock.release()
        self.queue.put_nowait((target, callback, name, args, kargs))
149149
protected void attemptFlush() throws SIRollbackException, SIConnectionLostException, SIResourceException, SIErrorException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc,"attemptFlush");

    //The FlushComplete callback
    FlushComplete callback = null;
    //The old set of streams which has just been flushed
    StreamSet oldStreamSet = null;

    // Actions for a flushable stream.  Note that we synchronize
    // up to step 4 to avoid races with threads handling control
    // messages.
    // 1. Cache and unset flushInProgress.
    // 2. Create a new stream ID
    // 3. Remove any data structures associated with the stream.
    // 4. Invoke the callback on the cached FlushComplete reference.
    synchronized (this)
    {
      // Resolve race between control message handlers who both
      // see a flushable stream.
      // flushInProgress was set by startFlush
      if (flushInProgress == null)
      {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "attemptFlush");
        return;
      }

      // Also verify that the stream really is flushable in case
      // a thread handling a control message called us with a
      // stale source stream reference.
      if (!flushable())
      {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "attemptFlush");
        return;
      }

      // Now cache the callback.  When we exit the synchronize block,
      // the flush will have officially ended.
      callback = flushInProgress;
      flushInProgress = null;

      // Cleanup the data structures and null out the
      // existing streamSet so we force creation of a new
      // set on the next message.
      oldStreamSet = streamSet;
      streamSet = null;

      if(oldStreamSet != null)
      {
        oldStreamSet.remove();
      }
    }

    // Send out a flushed message.  If this fails, make sure we get
    // to at least invoke the callback.
    try
    {
      // The Cellule argument is null as it is ignored by our parent handler
      // this flush message should be broadcast downstream.
      if (oldStreamSet != null)
        downControl.sendFlushedMessage(null, oldStreamSet.getStreamID());
    }
    catch (Exception e)
    {
      // FFDC
      FFDCFilter.processException(
        e,
        "com.ibm.ws.sib.processor.gd.SourceStreamManager.attemptFlush",
        "1:1158:1.102",
        this);

      // Note that it doesn't make much sense to throw an exception here since
      // this is a callback from stream array map.
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.exit(tc, "attemptFlush", e);
      return;
    }
    finally
    {
      // Invoke the calback in the finally clause so we don't holdup
      // whoever's waiting for the flush to complete.
      callback.flushComplete(destinationHandler);
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "attemptFlush");
  }
5657
protected function changeQueueCount($queueCounter)
    {
        if ($queueCounter < 0) {
            $queueCounter = 0;
        }
        $this->_poolClientQueueCounter = $queueCounter;
        //Automatically change client state to `ClientInterface::CLIENT_POOL_STATE_READY` on empty queue
        if ($this->_poolClientQueueCounter === 0 && $this->_poolClientState === PoolClientInterface::CLIENT_POOL_STATE_BUSY) {
            $this->changeState(PoolClientInterface::CLIENT_POOL_STATE_READY);
        } elseif ($this->_poolClientQueueCounter > 0 && $this->_poolClientState === PoolClientInterface::CLIENT_POOL_STATE_READY) {
            $this->changeState(PoolClientInterface::CLIENT_POOL_STATE_BUSY);
        }
        $this->emit(PoolClientInterface::CLIENT_POOL_EVENT_CHANGE_QUEUE, [$queueCounter]);
    }
481515
private boolean tryEnqueueAttempt(DelayedExecution<T> delayedExecution) {
    int rejectionThreshold = queueRejectionThreshold.get();
    if (rejectionThreshold < 0) {
      return requestQueue.offer(delayedExecution);
    }
    long stamp = stampedLock.readLock();
    try {
      while (requestQueue.size() < rejectionThreshold) {
        long writeStamp = stampedLock.tryConvertToWriteLock(stamp);
        if (writeStamp != 0L) {
          stamp = writeStamp;
          return requestQueue.offer(delayedExecution);
        } else {
          stampedLock.unlock(stamp);
          stamp = stampedLock.writeLock();
        }
      }
      return false;
    } finally {
      stampedLock.unlock(stamp);
    }
  }