Java 类com.google.common.util.concurrent.Runnables 实例源码

项目:reactive-grpc    文件:ClientCalls.java   
/**
 * Implements a stream -> unary call as {@link Flux} -> {@link Mono}, where the client transits a stream of
 * messages.
 */
public static <TRequest, TResponse> Mono<TResponse> manyToOne(
        Flux<TRequest> rxRequest,
        Function<StreamObserver<TResponse>, StreamObserver<TRequest>> delegate) {
    try {
        return Mono
                .<TResponse>create(emitter -> {
                    ReactiveProducerStreamObserver<TRequest, TResponse> reactiveProducerStreamObserver = new ReactiveProducerStreamObserver<>(
                            rxRequest,
                            emitter::success,
                            emitter::error,
                            Runnables.doNothing());
                    delegate.apply(
                            new CancellableStreamObserver<>(reactiveProducerStreamObserver,
                            reactiveProducerStreamObserver::cancel));
                    reactiveProducerStreamObserver.rxSubscribe();
                })
                .transform(Operators.lift(new SubscribeOnlyOnceLifter<TResponse>()));
    } catch (Throwable throwable) {
        return Mono.error(throwable);
    }
}
项目:pravega    文件:StreamSegmentContainerTests.java   
private CompletableFuture<Void> waitForSegmentInStorage(SegmentProperties metadataProps, TestContext context) {
    Function<SegmentProperties, Boolean> meetsConditions = storageProps ->
            storageProps.isSealed() == metadataProps.isSealed()
                    && storageProps.getLength() >= metadataProps.getLength()
                    && context.storageFactory.truncationOffsets.getOrDefault(metadataProps.getName(), 0L) >= metadataProps.getStartOffset();

    AtomicBoolean canContinue = new AtomicBoolean(true);
    TimeoutTimer timer = new TimeoutTimer(TIMEOUT);
    return Futures.loop(
            canContinue::get,
            () -> context.storage.getStreamSegmentInfo(metadataProps.getName(), TIMEOUT)
                                 .thenCompose(storageProps -> {
                             if (meetsConditions.apply(storageProps)) {
                                 canContinue.set(false);
                                 return CompletableFuture.completedFuture(null);
                             } else if (!timer.hasRemaining()) {
                                 return Futures.failedFuture(new TimeoutException());
                             } else {
                                 return Futures.delayedFuture(Duration.ofMillis(10), executorService());
                             }
                         }).thenRun(Runnables.doNothing()),
            executorService());
}
项目:salta    文件:BindingTest.java   
@Override
protected void configure() {
    // Linked.
    bind(Object.class).to(Runnable.class).in(Scopes.SINGLETON);

    // Instance.
    bind(Runnable.class).toInstance(Runnables.doNothing());

    // Provider instance.
    bind(Foo.class).toProvider(new Provider<Foo>() {
        @Override
        public Foo get() {
            return new Foo();
        }
    }).in(Scopes.SINGLETON);

    // Provider.
    bind(Foo.class).annotatedWith(named("provider"))
            .toProvider(FooProvider.class);

    // Class.
    bind(Bar.class).in(Scopes.SINGLETON);

    // Constant.
    bindConstant().annotatedWith(named("name")).to("Bob");
}
项目:gerrit    文件:RepoSequence.java   
public RepoSequence(
    GitRepositoryManager repoManager,
    GitReferenceUpdated gitRefUpdated,
    Project.NameKey projectName,
    String name,
    Seed seed,
    int batchSize) {
  this(
      repoManager,
      gitRefUpdated,
      projectName,
      name,
      seed,
      batchSize,
      Runnables.doNothing(),
      RETRYER);
}
项目:gerrit    文件:ExternalIdsUpdate.java   
private ExternalIdsUpdate(
    GitRepositoryManager repoManager,
    @Nullable AccountCache accountCache,
    AllUsersName allUsersName,
    MetricMaker metricMaker,
    ExternalIds externalIds,
    ExternalIdCache externalIdCache,
    PersonIdent committerIdent,
    PersonIdent authorIdent,
    @Nullable IdentifiedUser currentUser,
    GitReferenceUpdated gitRefUpdated) {
  this(
      repoManager,
      accountCache,
      allUsersName,
      metricMaker,
      externalIds,
      externalIdCache,
      committerIdent,
      authorIdent,
      currentUser,
      gitRefUpdated,
      Runnables.doNothing(),
      RETRYER);
}
项目:spring-boot-gae    文件:SearchServiceImpl.java   
@Nonnull
@Override
public <E> Runnable indexAsync(E entity, String id) {
    if (!searchMetadata.hasIndexedFields(entity.getClass())) {
        return Runnables.doNothing();
    }

    Index index = getIndex(entity.getClass());
    Document document = documentBuilder.apply(id, entity);

    return new IndexOperation(
            index.putAsync(document)
    );
}
项目:grpc-java-contrib    文件:LambdaStreamObserver.java   
public LambdaStreamObserver(Consumer<T> onNext, Consumer<Throwable> onError) {
    this(
        onNext,
        onError,
        Runnables.doNothing()
    );
}
项目:grpc-java-contrib    文件:LambdaStreamObserver.java   
public LambdaStreamObserver(Consumer<T> onNext) {
    this(
        onNext,
        t -> {
            throw new OnErrorNotImplementedException(t);
        },
        Runnables.doNothing()
    );
}
项目:science-journal    文件:ConnectableSensorRegistry.java   
public void reloadProvider(String providerKey, boolean startSpinners) {
    SensorDiscoverer discoverer = mDiscoverers.get(providerKey);
    if (discoverer == null) {
        throw new IllegalArgumentException(
                "Couldn't find " + providerKey + " in " + mDiscoverers);
    }
    startScanning(providerKey, discoverer, new TaskPool(Runnables.doNothing()),
            new HashSet<String>(), startSpinners);
}
项目:pravega    文件:OperationProcessorTests.java   
private MetadataCheckpointPolicy getNoOpCheckpointPolicy() {
    // Turn off any MetadataCheckpointing. In these tests, we are doing that manually.
    DurableLogConfig dlConfig = DurableLogConfig
            .builder()
            .with(DurableLogConfig.CHECKPOINT_COMMIT_COUNT, Integer.MAX_VALUE)
            .with(DurableLogConfig.CHECKPOINT_TOTAL_COMMIT_LENGTH, Long.MAX_VALUE)
            .build();

    return new MetadataCheckpointPolicy(dlConfig, Runnables.doNothing(), executorService());
}
项目:guice    文件:BindingTest.java   
@Override
protected void configure() {
  // Linked.
  bind(Object.class).to(Runnable.class).in(Scopes.SINGLETON);

  // Instance.
  bind(Runnable.class).toInstance(Runnables.doNothing());

  // Provider instance.
  bind(Foo.class)
      .toProvider(
          new Provider<Foo>() {
            @Override
            public Foo get() {
              return new Foo();
            }
          })
      .in(Scopes.SINGLETON);

  // Provider.
  bind(Foo.class)
      .annotatedWith(named("provider"))
      .toProvider(FooProvider.class);

  // Class.
  bind(Bar.class).in(Scopes.SINGLETON);

  // Constant.
  bindConstant().annotatedWith(named("name")).to("Bob");
}
项目:bazel    文件:ParallelBuilderTest.java   
@Test
public void testReportsActionExecutedEvent() throws Exception {
  Artifact pear = createDerivedArtifact("pear");
  ActionEventRecorder recorder = new ActionEventRecorder();
  eventBus.register(recorder);

  Action action = registerAction(new TestAction(Runnables.doNothing(), emptySet, asSet(pear)));

  buildArtifacts(createBuilder(DEFAULT_NUM_JOBS, true), pear);
  assertThat(recorder.actionExecutedEvents).hasSize(1);
  assertThat(recorder.actionExecutedEvents.get(0).getAction()).isEqualTo(action);
}
项目:bazel    文件:TreeArtifactBuildTest.java   
TreeArtifactTestAction(final SpecialArtifact output, final String... subOutputs) {
  this(Runnables.doNothing(),
      null,
      ImmutableList.<TreeFileArtifact>of(),
      output,
      Collections2.transform(
          Arrays.asList(subOutputs),
          new Function<String, TreeFileArtifact>() {
            @Nullable
            @Override
            public TreeFileArtifact apply(String s) {
              return ActionInputHelper.treeFileArtifact(output, s);
            }
          }));
}
项目:TabbyChat-2    文件:GuiNewChatTC.java   
private Runnable checkThread(Runnable runnable) {
    if (!mc.isCallingFromMinecraftThread()) {
        mc.addScheduledTask(runnable);
        TabbyChat.getLogger().warn("Tried to modify chat from thread {}. To prevent a crash, it has been scheduled on the main thread.", Thread.currentThread().getName(), new Exception());
        return Runnables.doNothing();
    }
    return runnable;
}
项目:buck    文件:ThreadsTest.java   
@Test
public void testNamedThread() {
  String name = "test";
  Runnable runnable = Runnables.doNothing();

  Thread thread = Threads.namedThread(name, runnable);

  assertNotNull(thread);
  assertFalse(thread.isDaemon());
  assertEquals(State.NEW, thread.getState());
  assertEquals(name, thread.getName());
}
项目:jimfs    文件:JimfsInputStreamTest.java   
private static JimfsInputStream newInputStream(int... bytes) throws IOException {
  byte[] b = new byte[bytes.length];
  for (int i = 0; i < bytes.length; i++) {
    b[i] = (byte) bytes[i];
  }

  RegularFile file = regularFile(0);
  file.write(0, b, 0, b.length);
  return new JimfsInputStream(file, new FileSystemState(Runnables.doNothing()));
}
项目:jimfs    文件:PollingWatchServiceTest.java   
@Before
public void setUp() {
  fs = (JimfsFileSystem) Jimfs.newFileSystem(Configuration.unix());
  watcher =
      new PollingWatchService(
          fs.getDefaultView(),
          fs.getPathService(),
          new FileSystemState(Runnables.doNothing()),
          4, MILLISECONDS);
}
项目:Reer    文件:FixedExclusiveModeCrossProcessCacheAccess.java   
@Override
public Runnable acquireFileLock() {
    return Runnables.doNothing();
}
项目:pravega    文件:CreateOperationTests.java   
/**
 * Tests CreateOperation for two concurrent Create requests on the same segment. This actually tests atomicCreate()
 * on FileSystemOperation.
 */
@Test
public void testAtomicCreate() throws Exception {
    @Cleanup
    val fs = new MockFileSystem();
    val context = newContext(1, fs);
    val path = context.getFileName(SEGMENT_NAME, 0);

    val wasInvoked = new AtomicBoolean(); // Verifies we don't invoke FileSystem.create() multiple times.
    val creationInvoked = new CompletableFuture<Void>(); // Completed when FileSystem.create() is in progress.
    val creationReleased = new CompletableFuture<Void>(); // Completed when ready to unblock FileSystem.create().
    val creationCompleted = new CompletableFuture<Void>(); // Completed when FileSystem.create() is done.
    fs.setOnCreate(p -> {
        Assert.assertFalse("Multiple invocations to FileSystem.create().", wasInvoked.getAndSet(true));
        creationInvoked.complete(null);
        return fs.new WaitAction(path, creationReleased);
    });

    // Execute the first create and wait for it to have been invoked (which means we should have registered the creation).
    val op1 = new AtomicCreateOperation(SEGMENT_NAME, context);
    ExecutorServiceHelpers.execute(
            () -> {
                op1.run();
                creationCompleted.complete(null);
            },
            ex -> Assert.fail("Unexpected exception on first call. " + ex),
            Runnables.doNothing(),
            ForkJoinPool.commonPool());
    creationInvoked.join();

    // Execute the second operation and verify it fails.
    val op2 = new AtomicCreateOperation(SEGMENT_NAME, context);
    AssertExtensions.assertThrows(
            "Second concurrent call did not fail with appropriate exception.",
            op2::run,
            ex -> ex instanceof FileAlreadyExistsException);

    // Complete the first creation, wait for it to actually be done, and verify the file has been created.
    creationReleased.complete(null);
    creationCompleted.join();
    checkFileExists(context);

    AssertExtensions.assertThrows(
            "Non-concurrent call did not fail with appropriate exception.",
            op2::run,
            ex -> ex instanceof FileAlreadyExistsException);
}
项目:gerrit    文件:RepoSequenceTest.java   
private RepoSequence newSequence(String name, int start, int batchSize) {
  return newSequence(name, start, batchSize, Runnables.doNothing(), RETRYER);
}
项目:scylla-tools-java    文件:LogTransaction.java   
static void waitForDeletions()
{
    FBUtilities.waitOnFuture(ScheduledExecutors.nonPeriodicTasks.schedule(Runnables.doNothing(), 0, TimeUnit.MILLISECONDS));
}
项目:scylla-tools-java    文件:CommitLogSegmentManager.java   
private void wakeManager()
{
    // put a NO-OP on the queue, to trigger management thread (and create a new segment if necessary)
    segmentManagementTasks.add(Runnables.doNothing());
}
项目:bazel    文件:FilesystemValueCheckerTest.java   
public void checkDirtyActions(BatchStat batchStatter, boolean forceDigests) throws Exception {
  Artifact out1 = createDerivedArtifact("fiz");
  Artifact out2 = createDerivedArtifact("pop");

  FileSystemUtils.writeContentAsLatin1(out1.getPath(), "hello");
  FileSystemUtils.writeContentAsLatin1(out2.getPath(), "fizzlepop");

  SkyKey actionLookupKey =
      new ActionLookupKey() {
        @Override
        public SkyFunctionName functionName() {
          return SkyFunctionName.FOR_TESTING;
        }
      };
  SkyKey actionKey1 = ActionExecutionValue.key(actionLookupKey, 0);
  SkyKey actionKey2 = ActionExecutionValue.key(actionLookupKey, 1);
  differencer.inject(
      ImmutableMap.<SkyKey, SkyValue>of(
          actionKey1,
              actionValue(
                  new TestAction(
                      Runnables.doNothing(), ImmutableSet.<Artifact>of(), ImmutableSet.of(out1)),
                  forceDigests),
          actionKey2,
              actionValue(
                  new TestAction(
                      Runnables.doNothing(), ImmutableSet.<Artifact>of(), ImmutableSet.of(out2)),
                  forceDigests)));
  assertThat(
          driver
              .evaluate(ImmutableList.<SkyKey>of(), false, 1, NullEventHandler.INSTANCE)
              .hasError())
      .isFalse();
  assertThat(new FilesystemValueChecker(null, null).getDirtyActionValues(evaluator.getValues(),
      batchStatter, ModifiedFileSet.EVERYTHING_MODIFIED)).isEmpty();

  FileSystemUtils.writeContentAsLatin1(out1.getPath(), "goodbye");
  assertThat(
          new FilesystemValueChecker(null, null)
              .getDirtyActionValues(
                  evaluator.getValues(), batchStatter, ModifiedFileSet.EVERYTHING_MODIFIED))
      .containsExactly(actionKey1);
  assertThat(
          new FilesystemValueChecker(null, null)
              .getDirtyActionValues(
                  evaluator.getValues(),
                  batchStatter,
                  new ModifiedFileSet.Builder().modify(out1.getExecPath()).build()))
      .containsExactly(actionKey1);
  assertThat(
          new FilesystemValueChecker(null, null).getDirtyActionValues(evaluator.getValues(),
              batchStatter,
              new ModifiedFileSet.Builder().modify(
                  out1.getExecPath().getParentDirectory()).build())).isEmpty();
  assertThat(
      new FilesystemValueChecker(null, null).getDirtyActionValues(evaluator.getValues(),
          batchStatter, ModifiedFileSet.NOTHING_MODIFIED)).isEmpty();
}
项目:bazel    文件:TreeArtifactBuildTest.java   
TouchingTestAction(TreeFileArtifact... outputPaths) {
  super(Runnables.doNothing(), outputPaths);
}
项目:bazel    文件:TreeArtifactBuildTest.java   
WriteInputToFilesAction(Artifact input, TreeFileArtifact... outputs) {
  this(Runnables.doNothing(), input, outputs);
}
项目:bazel    文件:TreeArtifactBuildTest.java   
CopyTreeAction(
    Collection<TreeFileArtifact> inputPaths,
    Collection<TreeFileArtifact> outputPaths) {
  super(Runnables.doNothing(), inputPaths, outputPaths);
}
项目:buck    文件:ThreadsTest.java   
@Test(expected = NullPointerException.class)
public void testNamedThreadWithNullName() {
  Threads.namedThread(null, Runnables.doNothing());
}
项目:jimfs    文件:JimfsOutputStreamTest.java   
private static JimfsOutputStream newOutputStream(boolean append) {
  RegularFile file = regularFile(0);
  return new JimfsOutputStream(file, append, new FileSystemState(Runnables.doNothing()));
}
项目:jimfs    文件:JimfsFileChannelTest.java   
private static FileChannel channel(RegularFile file, OpenOption... options) throws IOException {
  return new JimfsFileChannel(
      file,
      Options.getOptionsForChannel(ImmutableSet.copyOf(options)),
      new FileSystemState(Runnables.doNothing()));
}
项目:jimfs    文件:JimfsFileChannelTest.java   
@Test
public void testFileTimeUpdates() throws IOException {
  RegularFile file = regularFile(10);
  FileChannel channel =
      new JimfsFileChannel(
          file,
          ImmutableSet.<OpenOption>of(READ, WRITE),
          new FileSystemState(Runnables.doNothing()));

  // accessed
  long accessTime = file.getLastAccessTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.read(ByteBuffer.allocate(10));
  assertNotEquals(accessTime, file.getLastAccessTime());

  accessTime = file.getLastAccessTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.read(ByteBuffer.allocate(10), 0);
  assertNotEquals(accessTime, file.getLastAccessTime());

  accessTime = file.getLastAccessTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.read(new ByteBuffer[] {ByteBuffer.allocate(10)});
  assertNotEquals(accessTime, file.getLastAccessTime());

  accessTime = file.getLastAccessTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.read(new ByteBuffer[] {ByteBuffer.allocate(10)}, 0, 1);
  assertNotEquals(accessTime, file.getLastAccessTime());

  accessTime = file.getLastAccessTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.transferTo(0, 10, new ByteBufferChannel(10));
  assertNotEquals(accessTime, file.getLastAccessTime());

  // modified
  long modifiedTime = file.getLastModifiedTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.write(ByteBuffer.allocate(10));
  assertNotEquals(modifiedTime, file.getLastModifiedTime());

  modifiedTime = file.getLastModifiedTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.write(ByteBuffer.allocate(10), 0);
  assertNotEquals(modifiedTime, file.getLastModifiedTime());

  modifiedTime = file.getLastModifiedTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.write(new ByteBuffer[] {ByteBuffer.allocate(10)});
  assertNotEquals(modifiedTime, file.getLastModifiedTime());

  modifiedTime = file.getLastModifiedTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.write(new ByteBuffer[] {ByteBuffer.allocate(10)}, 0, 1);
  assertNotEquals(modifiedTime, file.getLastModifiedTime());

  modifiedTime = file.getLastModifiedTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.truncate(0);
  assertNotEquals(modifiedTime, file.getLastModifiedTime());

  modifiedTime = file.getLastModifiedTime();
  Uninterruptibles.sleepUninterruptibly(2, MILLISECONDS);

  channel.transferFrom(new ByteBufferChannel(10), 0, 10);
  assertNotEquals(modifiedTime, file.getLastModifiedTime());
}