Java Code Examples for com.google.common.util.concurrent.Futures#immediateCancelledFuture()

The following examples show how to use com.google.common.util.concurrent.Futures#immediateCancelledFuture() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PackagePipeline.java    From buck with Apache License 2.0 6 votes vote down vote up
private ListenableFuture<Package> computePackage(
    Cell cell, AbsPath packageFile, PackageMetadata pkg, Optional<Package> parentPkg)
    throws BuildTargetException {
  if (shuttingDown()) {
    return Futures.immediateCancelledFuture();
  }
  Package result;

  try (SimplePerfEvent.Scope scope =
      SimplePerfEvent.scopeIgnoringShortEvents(
          eventBus,
          perfEventId,
          "packageFile",
          packageFile,
          perfEventScope,
          minimumPerfEventTimeMs,
          TimeUnit.MILLISECONDS)) {

    result = PackageFactory.create(cell, packageFile.getPath(), pkg, parentPkg);
  }
  return Futures.immediateFuture(result);
}
 
Example 2
Source File: PackagePipeline.java    From buck with Apache License 2.0 6 votes vote down vote up
private ListenableFuture<Optional<Package>> getParentPackageJob(
    Cell cell, AbsPath childBuildFile) {
  if (shuttingDown()) {
    return Futures.immediateCancelledFuture();
  }

  Optional<AbsPath> parentBuildFile = getParentPackageFile(cell, childBuildFile);
  if (!parentBuildFile.isPresent()) {
    // childBuildFile is at the cell root and we have no more parents
    return Futures.immediateFuture(Optional.empty());
  }

  if (cell.getFilesystem().isFile(parentBuildFile.get())) {
    // We have a build file and should cache this package node
    return Futures.transformAsync(
        getPackageJobInternal(cell, parentBuildFile.get()),
        cachedPackageNode -> Futures.immediateFuture(Optional.of(cachedPackageNode)),
        executorService);
  } else {
    return getParentPackageJob(cell, parentBuildFile.get());
  }
}
 
Example 3
Source File: PackagePipeline.java    From buck with Apache License 2.0 6 votes vote down vote up
private ListenableFuture<Package> getPackageJobInternal(Cell cell, AbsPath packageFile)
    throws BuildTargetException {
  if (shuttingDown()) {
    return Futures.immediateCancelledFuture();
  }

  return cache.getJobWithCacheLookup(
      cell,
      packageFile,
      () ->
          Futures.transformAsync(
              getParentPackageJob(cell, packageFile),
              parentPkg ->
                  Futures.transformAsync(
                      getPackageFileManifest(cell, packageFile),
                      packageFileManifest ->
                          computePackage(
                              cell, packageFile, packageFileManifest.getPackage(), parentPkg),
                      executorService),
              executorService),
      eventBus);
}
 
Example 4
Source File: AsyncBackgroundTaskManager.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
Future<Unit> schedule(ManagedBackgroundTask<?> task) {
  if (!schedulingOpen.get()) {
    LOG.warn("Manager is not accepting new tasks; newly scheduled tasks will not be run.");
    return Futures.immediateCancelledFuture();
  }
  Class<?> actionClass = task.getActionClass();
  Optional.ofNullable(cancellableTasks.get(actionClass))
      .ifPresent(ManagedBackgroundTask::markToCancel);
  if (task.getShouldCancelOnRepeat()) {
    cancellableTasks.put(actionClass, task);
  }
  synchronized (scheduledTasks) {
    scheduledTasks.add(task);
    scheduledTasks.notify();
  }
  return task.getFuture();
}
 
Example 5
Source File: GenericFileParsePipeline.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<T> getFileJob(Cell cell, AbsPath buildFile) throws BuildTargetException {

  if (shuttingDown.get()) {
    return Futures.immediateCancelledFuture();
  }

  return cache.getJobWithCacheLookup(
      cell,
      buildFile,
      () -> {
        if (shuttingDown.get()) {
          return Futures.immediateCancelledFuture();
        }

        RelPath pathToCheck = cell.getRoot().relativize(buildFile.getParent());
        if (cell.getFilesystem().isIgnored(pathToCheck)) {
          throw new HumanReadableException(
              "Content of '%s' cannot be built because it is defined in an ignored directory.",
              pathToCheck);
        }

        return fileParserPool.getManifest(eventBus, cell, watchman, buildFile, executorService);
      },
      eventBus);
}
 
Example 6
Source File: ResourcePool.java    From buck with Apache License 2.0 5 votes vote down vote up
private synchronized ListenableFuture<Unit> scheduleNewResourceRequest() {
  if (closing.get()) {
    return Futures.immediateCancelledFuture();
  }
  SettableFuture<Unit> resourceFuture = SettableFuture.create();
  resourceRequests.add(resourceFuture);
  return resourceFuture;
}
 
Example 7
Source File: Teleporter.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public ListenableFuture<?> remoteTeleport(Player traveler, @Nullable String datacenter, @Nullable String serverName, @Nullable String bungeeName, boolean quiet) {
    final Audience audience = quiet ? NullAudience.INSTANCE : audiences.get(traveler);

    if(datacenter == null || !traveler.hasPermission(CROSS_DATACENTER_PERMISSION)) {
        datacenter = localServer.datacenter();
    }

    final BaseComponent fullName = ServerFormatter.light.nameWithDatacenter(datacenter, bungeeName, serverName, bungeeName == null);

    if((bungeeName == null && localServer.role() == ServerDoc.Role.LOBBY) ||
       (bungeeName != null && bungeeName.equals(localServer.bungee_name()))) {
        showCurrentServer(audience);
        return Futures.immediateFuture(null);
    }

    PlayerServerChangeEvent event = new PlayerServerChangeEvent(traveler, datacenter, bungeeName, new TranslatableComponent("servers.cannotChange"));
    traveler.getServer().getPluginManager().callEvent(event);

    if(event.isCancelled()) {
        if(event.getCancelMessage() != null) {
            audience.sendWarning(event.getCancelMessage(), false);
        }
        return Futures.immediateCancelledFuture();
    }

    audience.sendMessage(new Component(new TranslatableComponent("command.server.teleporting", fullName), ChatColor.DARK_PURPLE));
    return playerServerChanger.sendPlayerToServer(traveler, bungeeName, quiet);
}
 
Example 8
Source File: RestartManager.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public ListenableFuture<?> requestRestart(String reason, int priority) {
    if(this.isRestartRequested(priority)) {
        return Futures.immediateCancelledFuture();
    } else {
        final Instant now = Instant.now();
        logger.info("Requesting restart at " + now + ", because " + reason);
        return minecraftService.updateLocalServer(new ServerDoc.Restart() {
            @Override public Instant restart_queued_at() { return now; }
            @Override public String restart_reason() { return reason; }
            @Override public int restart_priority() { return priority; }
        });
    }
}
 
Example 9
Source File: RestartManager.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public ListenableFuture<?> cancelRestart() {
    if(this.isRestartRequested()) {
        return minecraftService.updateLocalServer(new ServerDoc.Restart() {
            @Override public Instant restart_queued_at() { return null; }
            @Override public String restart_reason() { return null; }
        });
    } else {
        return Futures.immediateCancelledFuture();
    }
}
 
Example 10
Source File: CompactionManager.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public Future<?> submitAntiCompaction(final ColumnFamilyStore cfs,
                                      final Collection<Range<Token>> ranges,
                                      final Refs<SSTableReader> sstables,
                                      final long repairedAt)
{
    Runnable runnable = new WrappedRunnable() {
        @Override
        public void runMayThrow() throws Exception
        {
            boolean success = false;
            while (!success)
            {
                for (SSTableReader compactingSSTable : cfs.getDataTracker().getCompacting())
                    sstables.releaseIfHolds(compactingSSTable);
                Set<SSTableReader> compactedSSTables = new HashSet<>();
                for (SSTableReader sstable : sstables)
                    if (sstable.isMarkedCompacted())
                        compactedSSTables.add(sstable);
                sstables.release(compactedSSTables);
                success = sstables.isEmpty() || cfs.getDataTracker().markCompacting(sstables);
            }
            performAnticompaction(cfs, ranges, sstables, repairedAt);
        }
    };
    if (executor.isShutdown())
    {
        logger.info("Compaction executor has shut down, not submitting anticompaction");
        return Futures.immediateCancelledFuture();
    }

    return executor.submit(runnable);
}
 
Example 11
Source File: CompactionManager.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public Future<?> submitCacheWrite(final AutoSavingCache.Writer writer)
{
    Runnable runnable = new Runnable()
    {
        public void run()
        {
            if (!AutoSavingCache.flushInProgress.add(writer.cacheType()))
            {
                logger.debug("Cache flushing was already in progress: skipping {}", writer.getCompactionInfo());
                return;
            }
            try
            {
                metrics.beginCompaction(writer);
                try
                {
                    writer.saveCache();
                }
                finally
                {
                    metrics.finishCompaction(writer);
                }
            }
            finally
            {
                AutoSavingCache.flushInProgress.remove(writer.cacheType());
            }
        }
    };
    if (executor.isShutdown())
    {
        logger.info("Executor has shut down, not submitting background task");
        Futures.immediateCancelledFuture();
    }
    return executor.submit(runnable);
}
 
Example 12
Source File: ReschedulingExecutor.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
public Future<?> schedule(String id, Runnable task, long delay, TimeUnit timeUnit) {
  if (active.get()) {
    ScheduledFuture<?> newFuture = executor.schedule(task, delay, timeUnit);
    log.debug("Scheduled ", id, ": ", task);
    Optional.ofNullable(tasks.put(id, newFuture)).ifPresent(oldFuture -> {
      log.debug("Cancelling ", id, " interrupt=", mayInterrupt, ": ", oldFuture);
      oldFuture.cancel(mayInterrupt);
      log.debug("Cancelled ", id, " interrupt=", mayInterrupt, ": ", oldFuture);
    });
    return newFuture;
  } else {
    log.debug("Schedule ", id, " while inactive: ", task);
    return Futures.immediateCancelledFuture();
  }
}
 
Example 13
Source File: UnconfiguredTargetNodeToTargetNodeParsePipeline.java    From buck with Apache License 2.0 5 votes vote down vote up
private ListenableFuture<TargetNodeMaybeIncompatible> dispatchComputeNode(
    Cell cell,
    BuildTarget buildTarget,
    DependencyStack dependencyStack,
    UnconfiguredTargetNode from)
    throws BuildTargetException {
  if (shuttingDown()) {
    return Futures.immediateCancelledFuture();
  }
  return Futures.immediateFuture(computeNode(cell, buildTarget, dependencyStack, from));
}
 
Example 14
Source File: SkyQueryEnvironment.java    From bazel with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <R> ListenableFuture<R> safeSubmitAsync(QueryTaskAsyncCallable<R> callable) {
  try {
    return Futures.submitAsync(() -> (ListenableFuture<R>) callable.call(), executor);
  } catch (RejectedExecutionException e) {
    return Futures.immediateCancelledFuture();
  }
}
 
Example 15
Source File: UnconfiguredTargetNodePipeline.java    From buck with Apache License 2.0 5 votes vote down vote up
private ListenableFuture<UnconfiguredTargetNode> dispatchComputeNode(
    Cell cell,
    UnconfiguredBuildTarget buildTarget,
    DependencyStack dependencyStack,
    Map<String, Object> from,
    Package pkg)
    throws BuildTargetException {
  if (shuttingDown()) {
    return Futures.immediateCancelledFuture();
  }
  UnconfiguredTargetNode result;

  try (Scope scope =
      SimplePerfEvent.scopeIgnoringShortEvents(
          eventBus,
          perfEventId,
          "target",
          buildTarget,
          perfEventScope,
          minimumPerfEventTimeMs,
          TimeUnit.MILLISECONDS)) {
    result =
        unconfiguredTargetNodeFactory.create(
            cell,
            cell.getBuckConfigView(ParserConfig.class)
                .getAbsolutePathToBuildFile(cell, buildTarget)
                .getPath(),
            buildTarget,
            dependencyStack,
            from,
            pkg);
  }
  return Futures.immediateFuture(result);
}
 
Example 16
Source File: SpawnIncludeScanner.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Executes grep-includes.
 *
 * @param input the file to parse
 * @param outputExecPath the output file (exec path)
 * @param inMemoryOutput if true, return the contents of the output in the return value instead of
 *     to the given Path
 * @param resourceOwner the resource owner
 * @param actionExecutionContext services in the scope of the action. Like the Err/Out stream
 *     outputs.
 * @param fileType Either "c++" or "swig", passed verbatim to grep-includes.
 * @return The InputStream of the .includes file if inMemoryOutput feature retrieved it directly.
 *     Otherwise "null"
 * @throws ExecException if scanning fails
 */
private static ListenableFuture<InputStream> spawnGrepAsync(
    Executor executor,
    Artifact input,
    PathFragment outputExecPath,
    boolean inMemoryOutput,
    ActionExecutionMetadata resourceOwner,
    ActionExecutionContext actionExecutionContext,
    Artifact grepIncludes,
    GrepIncludesFileType fileType) {
  ActionInput output = ActionInputHelper.fromPath(outputExecPath);
  NestedSet<? extends ActionInput> inputs =
      NestedSetBuilder.create(Order.STABLE_ORDER, grepIncludes, input);
  ImmutableSet<ActionInput> outputs = ImmutableSet.of(output);
  ImmutableList<String> command =
      ImmutableList.of(
          grepIncludes.getExecPathString(),
          input.getExecPath().getPathString(),
          outputExecPath.getPathString(),
          fileType.getFileType());

  ImmutableMap.Builder<String, String> execInfoBuilder = ImmutableMap.<String, String>builder();
  if (inMemoryOutput) {
    execInfoBuilder.put(
        ExecutionRequirements.REMOTE_EXECUTION_INLINE_OUTPUTS, outputExecPath.getPathString());
  }
  execInfoBuilder.put(ExecutionRequirements.DO_NOT_REPORT, "");

  Spawn spawn =
      new SimpleSpawn(
          resourceOwner,
          command,
          ImmutableMap.of(),
          execInfoBuilder.build(),
          inputs,
          outputs,
          LOCAL_RESOURCES);

  actionExecutionContext.maybeReportSubcommand(spawn);

  // Sharing the originalOutErr across spawnGrep calls would not be thread-safe. Instead, write
  // outerr to a temporary location and copy it back to the original after execution, using the
  // parent context as a lock to make it thread-safe (see dump() below).
  FileOutErr originalOutErr = actionExecutionContext.getFileOutErr();
  FileOutErr grepOutErr = originalOutErr.childOutErr();
  ActionExecutionContext grepContext = actionExecutionContext.withFileOutErr(grepOutErr);
  SpawnContinuation spawnContinuation;
  try {
    spawnContinuation =
        grepContext.getContext(SpawnStrategyResolver.class).beginExecution(spawn, grepContext);
  } catch (InterruptedException e) {
    dump(grepContext, actionExecutionContext);
    return Futures.immediateCancelledFuture();
  }
  SettableFuture<InputStream> future = SettableFuture.create();
  process(executor, future, spawnContinuation, output, grepContext, actionExecutionContext);
  return future;
}
 
Example 17
Source File: AbstractQueryEnvironment.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public <R> QueryTaskFuture<R> immediateCancelledFuture() {
  return new QueryTaskFutureImpl<>(Futures.<R>immediateCancelledFuture());
}
 
Example 18
Source File: RakNetConnection.java    From Cleanstone with MIT License 4 votes vote down vote up
@Override
public Future<Void> sendPacket(Packet packet) {
    // TODO
    return Futures.immediateCancelledFuture();
}
 
Example 19
Source File: CompactionManager.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public Future<?> submitUserDefined(final ColumnFamilyStore cfs, final Collection<Descriptor> dataFiles, final int gcBefore)
{
    Runnable runnable = new WrappedRunnable()
    {
        protected void runMayThrow() throws IOException
        {
            // look up the sstables now that we're on the compaction executor, so we don't try to re-compact
            // something that was already being compacted earlier.
            Collection<SSTableReader> sstables = new ArrayList<SSTableReader>(dataFiles.size());
            for (Descriptor desc : dataFiles)
            {
                // inefficient but not in a performance sensitive path
                SSTableReader sstable = lookupSSTable(cfs, desc);
                if (sstable == null)
                {
                    logger.info("Will not compact {}: it is not an active sstable", desc);
                }
                else
                {
                    sstables.add(sstable);
                }
            }

            if (sstables.isEmpty())
            {
                logger.info("No files to compact for user defined compaction");
            }
            else
            {
                AbstractCompactionTask task = cfs.getCompactionStrategy().getUserDefinedTask(sstables, gcBefore);
                if (task != null)
                    task.execute(metrics);
            }
        }
    };
    if (executor.isShutdown())
    {
        logger.info("Compaction executor has shut down, not submitting task");
        return Futures.immediateCancelledFuture();
    }

    return executor.submit(runnable);
}
 
Example 20
Source File: RakNetConnection.java    From Cleanstone with MIT License 4 votes vote down vote up
@Override
public Future<Void> close() {
    // TODO
    return Futures.immediateCancelledFuture();
}