Must be called from synchronized block
7096
private void redistributeBuffers() throws IOException {
		assert Thread.holdsLock(factoryLock);

		// All buffers, which are not among the required ones
		final int numAvailableMemorySegment = totalNumberOfMemorySegments - numTotalRequiredBuffers;

		if (numAvailableMemorySegment == 0) {
			// in this case, we need to redistribute buffers so that every pool gets its minimum
			for (LocalBufferPool bufferPool : allBufferPools) {
				bufferPool.setNumBuffers(bufferPool.getNumberOfRequiredMemorySegments());
			}
			return;
		}

		/*
		 * With buffer pools being potentially limited, let's distribute the available memory
		 * segments based on the capacity of each buffer pool, i.e. the maximum number of segments
		 * an unlimited buffer pool can take is numAvailableMemorySegment, for limited buffer pools
		 * it may be less. Based on this and the sum of all these values (totalCapacity), we build
		 * a ratio that we use to distribute the buffers.
		 */

		long totalCapacity = 0; // long to avoid int overflow

		for (LocalBufferPool bufferPool : allBufferPools) {
			int excessMax = bufferPool.getMaxNumberOfMemorySegments() -
				bufferPool.getNumberOfRequiredMemorySegments();
			totalCapacity += Math.min(numAvailableMemorySegment, excessMax);
		}

		// no capacity to receive additional buffers?
		if (totalCapacity == 0) {
			return; // necessary to avoid div by zero when nothing to re-distribute
		}

		// since one of the arguments of 'min(a,b)' is a positive int, this is actually
		// guaranteed to be within the 'int' domain
		// (we use a checked downCast to handle possible bugs more gracefully).
		final int memorySegmentsToDistribute = MathUtils.checkedDownCast(
				Math.min(numAvailableMemorySegment, totalCapacity));

		long totalPartsUsed = 0; // of totalCapacity
		int numDistributedMemorySegment = 0;
		for (LocalBufferPool bufferPool : allBufferPools) {
			int excessMax = bufferPool.getMaxNumberOfMemorySegments() -
				bufferPool.getNumberOfRequiredMemorySegments();

			// shortcut
			if (excessMax == 0) {
				continue;
			}

			totalPartsUsed += Math.min(numAvailableMemorySegment, excessMax);

			// avoid remaining buffers by looking at the total capacity that should have been
			// re-distributed up until here
			// the downcast will always succeed, because both arguments of the subtraction are in the 'int' domain
			final int mySize = MathUtils.checkedDownCast(
					memorySegmentsToDistribute * totalPartsUsed / totalCapacity - numDistributedMemorySegment);

			numDistributedMemorySegment += mySize;
			bufferPool.setNumBuffers(bufferPool.getNumberOfRequiredMemorySegments() + mySize);
		}

		assert (totalPartsUsed == totalCapacity);
		assert (numDistributedMemorySegment == memorySegmentsToDistribute);
	}
251306
@Override
	public E take() throws InterruptedException {
		synchronized (waiting) {
			if (closed) throw new InterruptedException("Channel closed");
			waiting.add(Thread.currentThread());
		}
		E e = super.take();
		synchronized (waiting) {
			waiting.remove(Thread.currentThread());
		}
		return e;
	}
1027300
public final void unblock() {
		if (Threading.debugSynchronization) ThreadingDebugHelper.unblocked(this);
		ArrayList<Runnable> listeners;
		synchronized (this) {
			if (unblocked) return;
			unblocked = true;
			if (listenersInline == null) {
				this.notifyAll();
				return;
			}
			listeners = listenersInline;
			listenersInline = new ArrayList<>(2);
		}
		Logger log = LCCore.getApplication().getLoggerFactory().getLogger(SynchronizationPoint.class);
		while (true) {
			if (!log.debug())
				for (int i = 0; i < listeners.size(); ++i)
					try { listeners.get(i).run(); }
					catch (Throwable t) { log.error(
						"Exception thrown by an inline listener of SynchronizationPoint", t); }
			else
				for (int i = 0; i < listeners.size(); ++i) {
					long start = System.nanoTime();
					try { listeners.get(i).run(); }
					catch (Throwable t) { log.error(
						"Exception thrown by an inline listener of SynchronizationPoint", t); }
					long time = System.nanoTime() - start;
					if (time > 1000000) // more than 1ms
						log.debug("Listener took " + (time / 1000000.0d) + "ms: " + listeners.get(i));
				}
			synchronized (this) {
				if (listenersInline.isEmpty()) {
					listenersInline = null;
					listeners = null;
					this.notifyAll();
					break;
				}
				listeners.clear();
				ArrayList<Runnable> tmp = listeners;
				listeners = listenersInline;
				listenersInline = tmp;
			}
		}
	}
786334
@FFDCIgnore(Throwable.class)
    @Override
    public T call() throws Exception {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        if (future.isCancelled()) {
            if (trace && tc.isDebugEnabled())
                Tr.debug(this, tc, "canceled - not running the task");
            return null;
        }

        Result result = resultRef.get(), resultForThisExecution = result;
        Status<T> skipped = null;
        Status<T> status;
        boolean done = false;
        T taskResult = null;
        ArrayList<ThreadContext> contextAppliedToThread = null;
        resultForThisExecution.executionThread = Thread.currentThread();
        try {
            // EE Concurrency 3.2.6.1: All tasks submitted to an executor must not run if task's component is not started.
            // ThreadContextDescriptor.taskStarting covers this requirement for us.
            contextAppliedToThread = threadContextDescriptor.taskStarting();

            // Determine if task should be skipped
            if (trigger != null)
                try {
                    if (trigger.skipRun(lastExecution, new Date(nextExecutionTime)))
                        skipped = new Status<T>(Status.Type.SKIPPED, null, null, false);
                } catch (Throwable x) {
                    // spec requires skip when skipRun fails
                    Tr.error(tc, "CWWKC1103.skip.run.failed", getName(), managedExecSvc.name, x);
                    skipped = new Status<T>(Status.Type.SKIPPED, null, x, false);
                }

            Date nextExecutionDate = null;

            // Run task if it wasn't skipped
            if (skipped == null) {
                // notify listener: taskStarting
                if (listener != null)
                    try {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                            Tr.event(this, tc, "taskStarting", managedExecSvc, task);
                        listener.taskStarting(future, managedExecSvc, task);
                    } finally {
                        done = result.getStatus().type == Status.Type.CANCELED;
                    }

                // run the task if the listener didn't cancel it
                status = result.getStatus();
                if (status.type == Status.Type.SUBMITTED && result.compareAndSet(status, new Status<T>(Status.Type.STARTED, null, null, false))) {
                    try {
                        if (trigger == null)
                            if (isCallable)
                                taskResult = ((Callable<T>) task).call();
                            else
                                ((Runnable) task).run();
                        else {
                            long startTime = System.currentTimeMillis();

                            if (isCallable)
                                taskResult = ((Callable<T>) task).call();
                            else
                                ((Runnable) task).run();

                            long endTime = System.currentTimeMillis();
                            String identityName = threadContextDescriptor.getExecutionProperties().get(ManagedTask.IDENTITY_NAME);
                            lastExecution = new LastExecutionImpl(identityName, nextExecutionTime, startTime, endTime, taskResult);
                        }
                    } catch (Throwable x) {
                        Tr.error(tc, "CWWKC1101.task.failed", getName(), managedExecSvc.name, x);
                        status = result.getStatus();
                        if (status.type == Status.Type.CANCELED) // include the failure in the result so it will be available to taskDone
                            result.compareAndSet(status, new Status<T>(Status.Type.CANCELED, null, x, true));
                        else if (status.type == Status.Type.STARTED)
                            result.compareAndSet(status, new Status<T>(Status.Type.DONE, null, x, true));
                        result.latch.countDown();
                    }

                    status = result.getStatus();
                    if (status.type == Status.Type.STARTED) {
                        // calculate next execution
                        if (trigger == null)
                            result.compareAndSet(status, new Status<T>(Status.Type.DONE, taskResult, null, fixedDelay == null && fixedRate == null));
                        else {
                            nextExecutionDate = trigger.getNextRunTime(lastExecution, taskScheduledTime);
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                Tr.debug(this, tc, "getNextRunTime", trigger, lastExecution,
                                         "taskScheduled " + Utils.toString(taskScheduledTime),
                                         "nextRunTime = " + Utils.toString(nextExecutionDate));

                            result.compareAndSet(status, new Status<T>(Status.Type.DONE, taskResult, null, nextExecutionDate == null));
                        }

                        result.latch.countDown();
                    }

                    done = true;

                    if (listener != null)
                        try {
                            if (status.type == Status.Type.CANCELED)
                                try {
                                    CancellationException cancelX = new CancellationException(Tr.formatMessage(tc, "CWWKC1110.task.canceled", getName(), managedExecSvc.name));
                                    if (trace && tc.isEventEnabled())
                                        Tr.event(this, tc, "taskCanceled", managedExecSvc, task, cancelX);
                                    listener.taskAborted(future, managedExecSvc, task, cancelX);
                                } catch (Throwable x) {
                                    Tr.error(tc, "CWWKC1102.listener.failed", getName(), managedExecSvc.name, x);
                                }

                            Throwable failure = result.getStatus().failure;
                            if (trace && tc.isEventEnabled())
                                Tr.event(this, tc, "taskDone", managedExecSvc, task, failure);
                            listener.taskDone(future, managedExecSvc, task, failure);
                        } catch (Throwable x) {
                            Tr.error(tc, "CWWKC1102.listener.failed", getName(), managedExecSvc.name, x);
                        }
                }
            } else {
                // Skip this execution (only possible if using a trigger)
                try {
                    status = result.getStatus();
                    if (status.type == Status.Type.SUBMITTED)
                        result.compareAndSet(status, skipped);

                    // calculate next execution
                    nextExecutionDate = trigger.getNextRunTime(lastExecution, taskScheduledTime);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(this, tc, "getNextRunTime", trigger, lastExecution,
                                 "taskScheduled " + Utils.toString(taskScheduledTime),
                                 "nextRunTime = " + Utils.toString(nextExecutionDate));

                    // No next execution
                    if (nextExecutionDate == null)
                        result.compareAndSet(skipped, new Status<T>(Status.Type.SKIPPED, null, skipped.failure, true));
                } finally {
                    result.latch.countDown();

                    // notify listener: taskAborted
                    if (listener != null) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                            Tr.event(this, tc, "taskAborted(skipped)", managedExecSvc, task);
                        listener.taskAborted(future, managedExecSvc, task, new SkippedException(skipped.failure));
                    }
                }

                // notify listener: taskDone
                if (listener != null) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                        Tr.event(this, tc, "taskDone(skipped)", managedExecSvc, task);
                    listener.taskDone(future, managedExecSvc, task, null);
                }
            }

            // Resubmit this task to run at the next scheduled time
            status = result.getStatus();
            if (!status.finalExecutionIsComplete && (status.type == Status.Type.DONE || status.type == Status.Type.SKIPPED)) {
                if (trace && tc.isEventEnabled())
                    Tr.event(this, tc, "DONE-->NONE (reset for next result)");
                resultRef.set(result = new Result());
                done = false;

                // compute the delay and estimate the next execution time
                long delay;
                if (fixedDelay != null) {
                    delay = fixedDelay;
                    nextExecutionTime = System.nanoTime() + unit.toNanos(delay);
                } else if (fixedRate != null) {
                    // Time elapsed from when the task should have started for the first time
                    long nanoTime = System.nanoTime();
                    long elapsed = unit.convert(nanoTime - taskScheduledNanos, TimeUnit.NANOSECONDS) - initialDelay;
                    delay = ((elapsed / fixedRate) + 1) * fixedRate - elapsed;
                    nextExecutionTime = nanoTime + unit.toNanos(delay);
                } else {
                    nextExecutionTime = nextExecutionDate.getTime();
                    delay = nextExecutionTime - System.currentTimeMillis();
                }

                if (delay < 0)
                    delay = 0;

                // notify listener: taskSubmitted
                if (listener != null)
                    try {
                        result.executionThread = Thread.currentThread();
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                            Tr.event(this, tc, "taskSubmitted", managedExecSvc, task);
                        listener.taskSubmitted(future, managedExecSvc, task);
                    } finally {
                        result.executionThread = null;
                    }

                // reschedule the task if the listener didn't cancel it
                status = result.getStatus();
                if (status.type == Status.Type.NONE && result.compareAndSet(status, new Status<T>(Status.Type.SUBMITTED, null, null, false))) {
                    if (trace && tc.isDebugEnabled())
                        Tr.debug(this, tc, "reschedule " + delay + ' ' + unit + " from now");
                    ScheduledFuture<?> scheduledFuture = managedExecSvc.scheduledExecSvc.schedule(this, delay, unit);
                    future.scheduledFutureRef.set(scheduledFuture);
                }
            }
        } catch (Throwable x) {
            // Some cases where this can happen:
            // component that scheduled the task is no longer available
            // listener.taskAborted (for skipped task) fails
            // trigger.getNextRunTime (for reschedule after skip) fails
            // listener.taskStarting fails
            // trigger.getNextRunTime (for reschedule after success) fails
            // taskAborted or taskDone fails
            // Liberty scheduled executor unavailable, or it fails to schedule

            if (contextAppliedToThread == null && x instanceof IllegalStateException && FrameworkState.isStopping()) {
                if (trace && tc.isDebugEnabled())
                    Tr.debug(this, tc, "Task not started due to server shutdown", getName(), x);
            } else
                Tr.error(tc, "CWWKC1101.task.failed", getName(), managedExecSvc.name, x);

            status = result.getStatus();
            if (!status.finalExecutionIsComplete) {
                Status<T> newStatus = status.type == Status.Type.STARTED ? new Status<T>(Status.Type.DONE, null, x, true) : new Status<T>(Status.Type.ABORTED, null, x, true);
                result.compareAndSet(status, newStatus);
            }
            result.latch.countDown();

            if (listener != null && !done)
                try {
                    try {
                        if (skipped == null && status.type != Status.Type.STARTED) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                                Tr.event(this, tc, "taskAborted", managedExecSvc);
                            listener.taskAborted(future, managedExecSvc, task, new AbortedException(x));
                        }
                    } finally {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                            Tr.event(this, tc, "taskDone", managedExecSvc, task, x);
                        listener.taskDone(future, managedExecSvc, task, x);
                    }
                } catch (Throwable t) {
                    // Log message, but otherwise ignore because we want to the original failure to be raised
                    Tr.error(tc, "CWWKC1102.listener.failed", getName(), managedExecSvc.name, x);
                }

            if (x instanceof Exception)
                throw (Exception) x;
            else
                throw (Error) x;
        } finally {
            resultForThisExecution.executionThread = null;
            if (contextAppliedToThread != null)
                threadContextDescriptor.taskStopping(contextAppliedToThread);
        }

        return taskResult;
    }
1212803
@Override
    public void flushQueueBlocking() {
        flushQueue();

        val context =((CudaContext) AtomicAllocator.getInstance().getDeviceContext().getContext());

        context.syncSpecialStream();
        context.syncOldStream();
    }
1006859
public void sync(final String path, VoidCallback cb, Object ctx) {
        verbotenThreadCheck();
        final String clientPath = path;
        PathUtils.validatePath(clientPath);

        final String serverPath = prependChroot(clientPath);

        RequestHeader h = new RequestHeader();
        h.setType(ZooDefs.OpCode.sync);
        SyncRequest request = new SyncRequest();
        SyncResponse response = new SyncResponse();
        request.setPath(serverPath);
        cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
                clientPath, serverPath, ctx, null);
    }
870152
void writeLock(int count) {
      if (count > 0 && counter != null)
         counter.acquireShared(count);
      sync.acquireShared(1);
   }
39775
@Override
    public Boolean call() throws Exception {
        error.set(null);
        
        List<Callable<Boolean>> subtasks = Lists.newArrayList();
        
        // We are iterating the entire ring using an arbitrary number of threads
        if (this.concurrencyLevel != null || startToken != null|| endToken != null) {
            List<TokenRange> tokens = partitioner.splitTokenRange(
                    startToken == null ? partitioner.getMinToken() : startToken, 
                    endToken == null   ? partitioner.getMinToken() : endToken, 
                    this.concurrencyLevel == null ? 1 : this.concurrencyLevel);
            
            for (TokenRange range : tokens) {
                subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken()));
            }
        }
        // We are iterating through each token range
        else {
            List<TokenRange> ranges = keyspace.describeRing(dc, rack);
            for (TokenRange range : ranges) {
                if (range.getStartToken().equals(range.getEndToken())) 
                    subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken()));
                else
                    subtasks.add(makeTokenRangeTask(partitioner.getTokenMinusOne(range.getStartToken()), range.getEndToken()));
            }
        }
        
        try {
            // Use a local executor
            if (executor == null) {
                ExecutorService localExecutor = Executors
                        .newFixedThreadPool(subtasks.size(),
                            new ThreadFactoryBuilder().setDaemon(true)
                                .setNameFormat("AstyanaxAllRowsReader-%d")
                                .build());
                
                try {
                    futures.addAll(startTasks(localExecutor, subtasks));
                    return waitForTasksToFinish();
                }
                finally {
                    localExecutor.shutdownNow();
                }
            }
            // Use an externally provided executor
            else {
                futures.addAll(startTasks(executor, subtasks));
                return waitForTasksToFinish();
            }
        }
        catch (Exception e) {
            error.compareAndSet(null, e);
            LOG.warn("AllRowsReader terminated. " + e.getMessage(), e);
            cancel();
            
            throw error.get();
        }
    }
1203439
@Override
    public void synchronizeThreadDevice(Long threadId, Integer deviceId, AllocationPoint point) {
        // we synchronize only if this AllocationPoint was used within device context, so for multiple consequent syncs only first one will be issued
        flowController.synchronizeToHost(point);
    }
665800
public void dispatchAsynchException(ProxyQueue proxyQueue, Exception exception)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "dispatchAsynchException",
                                           new Object[] { proxyQueue, exception });

      // Create a runnable with the data
      AsynchExceptionThread thread = new AsynchExceptionThread(proxyQueue, exception);
      dispatchThread(thread);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "dispatchAsynchException");
   }
601229
void execute() {
    boolean scheduleTaskRunner = false;
    synchronized (this) {
      if (!isThreadScheduled) {
        isThreadScheduled = true;
        scheduleTaskRunner = true;
      }
    }
    if (scheduleTaskRunner) {
      try {
        executor.execute(this);
      } catch (RuntimeException e) {
        // reset state in case of an error so that later calls to execute will actually do something
        synchronized (this) {
          isThreadScheduled = false;
        }
        // Log it and keep going.
        logger.log(
            Level.SEVERE,
            "Exception while running callbacks for " + listener + " on " + executor, 
            e);
        throw e;
      }
    }
  }
1147941
public synchronized boolean sync() {
		if (!validState) {
			throw new InvalidStateException();
		}
		try {
			fc.force(false);
			return true;
		} catch (Exception e) {
			log.error("Exception in sync()", e);
		}
		return false;
	}
790099
void waitNewLeaderAckFromQuorum()
      throws TimeoutException, InterruptedException, IOException {
    LOG.debug("Waiting for synchronization to followers complete.");
    int completeCount = 0;
    Zxid lastZxid = persistence.getLatestZxid();
    while (completeCount < this.quorumMap.size()) {
      // Here we should use sync_timeout.
      MessageTuple tuple = filter.getExpectedMessage(MessageType.ACK, null,
                                                     getSyncTimeoutMs());
      ZabMessage.Ack ack = tuple.getMessage().getAck();
      String source =tuple.getServerId();
      Zxid zxid = MessageBuilder.fromProtoZxid(ack.getZxid());
      if (!this.quorumMap.containsKey(source)) {
        LOG.warn("Quorum set doesn't contain {}, a bug?", source);
        continue;
      }
      if (zxid.compareTo(lastZxid) != 0) {
        LOG.error("The follower {} is not correctly synchronized.", source);
        throw new RuntimeException("The synchronized follower's last zxid"
            + "doesn't match last zxid of current leader.");
      }
      PeerHandler ph = this.quorumMap.get(source);
      ph.setLastAckedZxid(zxid);
      completeCount++;
    }
  }
6213
@Override
  public void flush(boolean forceSync)
      throws IOException {
    if (blockDataWriter != null) {
      blockDataWriter.flush();
      if (forceSync) {
        blockDataWriter.force(true);
      }
    }
  }
87761
public void lock() {
		if (cancel != null)
			return;
		if (error != null)
			return;
		Thread t;
		BlockedThreadHandler blockedHandler;
		do {
			synchronized (this) {
				if (!locked) {
					locked = true;
					return;
				}
				t = Thread.currentThread();
				blockedHandler = Threading.getBlockedThreadHandler(t);
				if (blockedHandler != null) break;
				try { this.wait(0); }
				catch (InterruptedException e) { continue; }
			}
		} while (true);
		blockedHandler.blocked(this, 0);
	}
971623
private void waitFor( long millis )
    {
        Object lock = new Object();
        synchronized ( lock )
        {
            try
            {
                lock.wait( millis );
            }
            catch ( InterruptedException e )
            {
                Thread.currentThread().interrupt(); // good practice if don't throw
                getLog().warn( "Spuriously interrupted while waiting for " + millis + "ms", e );
            }
        }
    }
936829
protected void onRPCError(int asyncHandle, int asyncError, String text) {
        IAsyncRPCEvent callback = getCallback(asyncHandle);
        
        if (callback != null) {
            callback.onRPCError(asyncHandle, asyncError, text);
        }
    }