com.google.common.util.concurrent.Service类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(7.6k)|赞(0)|评价(0)|浏览(326)

本文整理了Java中com.google.common.util.concurrent.Service类的一些代码示例,展示了Service类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Service类的具体详情如下:
包路径:com.google.common.util.concurrent.Service
类名称:Service

Service介绍

[英]An object with an operational state, plus asynchronous #startAsync() and #stopAsync() lifecycle methods to transition between states. Example services include webservers, RPC servers and timers.

The normal lifecycle of a service is:

  • State#NEW ->
  • State#STARTING ->
  • State#RUNNING ->
  • State#STOPPING ->
  • State#TERMINATED

There are deviations from this if there are failures or if Service#stopAsync is called before the Service reaches the State#RUNNING state. The set of legal transitions form a DAG, therefore every method of the listener will be called at most once. N.B. The State#FAILEDand State#TERMINATED states are terminal states, once a service enters either of these states it cannot ever leave them.

Implementors of this interface are strongly encouraged to extend one of the abstract classes in this package which implement this interface and make the threading and state management easier.
[中]一个具有操作状态的对象,加上异步的#startAsync()和#stopAsync()生命周期方法来在状态之间转换。示例服务包括Web服务器、RPC服务器和计时器。
服务的正常生命周期是:
*州#新->
*状态#开始->
*状态#运行->
*状态#停止->
*州#终止
如果出现故障,或者在服务到达#运行状态之前调用了服务#stopAsync,则会出现与此不同的情况。合法转换的集合形成一个{$0$},因此监听器的每个方法最多只能被调用一次。注意:状态#failed和状态#TERMINATED状态是终端状态,一旦服务进入这两种状态中的任何一种,它就永远无法离开它们。
强烈建议该接口的实现者扩展该包中的一个抽象类,这些抽象类实现了该接口,并使线程和状态管理更容易。

代码示例

代码示例来源:origin: google/guava

/** @since 15.0 */
@Override
public final void awaitRunning() {
 delegate.awaitRunning();
}

代码示例来源:origin: Graylog2/graylog2-server

@Override
public void doStop() {
  if (generatorService == null || !generatorService.isRunning()) {
    log.error("Cannot stop generator transport, it isn't running.");
    return;
  }
  log.debug("Stopping generator transport service {}", generatorService);
  generatorService.stopAsync().awaitTerminated();
  generatorService = null;
}

代码示例来源:origin: google/guava

/** @since 13.0 */
@Override
public final void addListener(Listener listener, Executor executor) {
 delegate.addListener(listener, executor);
}

代码示例来源:origin: spotify/helios

private void stopQuietly(final Service service) {
 if (service == null) {
  return;
 }
 try {
  service.stopAsync().awaitTerminated();
 } catch (Exception ignore) {
  // ignored
 }
}

代码示例来源:origin: google/guava

/**
 * Initiates service {@linkplain Service#startAsync startup} on all the services being managed. It
 * is only valid to call this method if all of the services are {@linkplain State#NEW new}.
 *
 * @return this
 * @throws IllegalStateException if any of the Services are not {@link State#NEW new} when the
 *     method is called.
 */
@CanIgnoreReturnValue
public ServiceManager startAsync() {
 for (Service service : services) {
  State state = service.state();
  checkState(state == NEW, "Service %s is %s, cannot start it.", service, state);
 }
 for (Service service : services) {
  try {
   state.tryStartTiming(service);
   service.startAsync();
  } catch (IllegalStateException e) {
   // This can happen if the service has already been started or stopped (e.g. by another
   // service or listener). Our contract says it is safe to call this method if
   // all services were NEW when it was called, and this has already been verified above, so we
   // don't propagate the exception.
   logger.log(Level.WARNING, "Unable to start Service " + service, e);
  }
 }
 return this;
}

代码示例来源:origin: google/guava

public void testDefaultService() throws InterruptedException {
 WaitOnRunService service = new WaitOnRunService();
 service.startAsync().awaitRunning();
 enterRun.await();
 service.stopAsync().awaitTerminated();
}

代码示例来源:origin: google/guava

/** @since 15.0 */
@CanIgnoreReturnValue
@Override
public final Service stopAsync() {
 delegate.stopAsync();
 return this;
}

代码示例来源:origin: google/guava

@Override
 public synchronized void failed(State from, Throwable failure) {
  assertEquals(from, Iterables.getLast(stateHistory));
  stateHistory.add(State.FAILED);
  assertEquals(State.FAILED, service.state());
  assertEquals(failure, service.failureCause());
  if (from == State.STARTING) {
   try {
    service.awaitRunning();
    fail();
   } catch (IllegalStateException e) {
    assertThat(e).hasCauseThat().isEqualTo(failure);
   }
  }
  try {
   service.awaitTerminated();
   fail();
  } catch (IllegalStateException e) {
   assertThat(e).hasCauseThat().isEqualTo(failure);
  }
  completionLatch.countDown();
 }
}

代码示例来源:origin: google/guava

/** @since 15.0 */
@CanIgnoreReturnValue
@Override
public final Service startAsync() {
 delegate.startAsync();
 return this;
}

代码示例来源:origin: google/guava

public void testTimeout() {
 // Create a service whose executor will never run its commands
 Service service =
   new AbstractExecutionThreadService() {
    @Override
    protected void run() throws Exception {}
    @Override
    protected ScheduledExecutorService executor() {
     return TestingExecutors.noOpScheduledExecutor();
    }
    @Override
    protected String serviceName() {
     return "Foo";
    }
   };
 try {
  service.startAsync().awaitRunning(1, TimeUnit.MILLISECONDS);
  fail("Expected timeout");
 } catch (TimeoutException e) {
  assertThat(e)
    .hasMessageThat()
    .isEqualTo("Timed out waiting for Foo [STARTING] to reach the RUNNING state.");
 }
}

代码示例来源:origin: google/guava

public void testCustomScheduler_deadlock() throws InterruptedException, BrokenBarrierException {
 final CyclicBarrier inGetNextSchedule = new CyclicBarrier(2);
 // This will flakily deadlock, so run it multiple times to increase the flake likelihood
 for (int i = 0; i < 1000; i++) {
  Service service =
    new AbstractScheduledService() {
     @Override
     protected void runOneIteration() {}
     @Override
     protected Scheduler scheduler() {
      return new CustomScheduler() {
       @Override
       protected Schedule getNextSchedule() throws Exception {
        if (state() != State.STARTING) {
         inGetNextSchedule.await();
         Thread.yield();
         throw new RuntimeException("boom");
        }
        return new Schedule(0, TimeUnit.NANOSECONDS);
       }
      };
     }
    };
  service.startAsync().awaitRunning();
  inGetNextSchedule.await();
  service.stopAsync();
 }
}

代码示例来源:origin: google/guava

@Override
public synchronized void running() {
 assertEquals(State.STARTING, Iterables.getOnlyElement(stateHistory));
 stateHistory.add(State.RUNNING);
 service.awaitRunning();
 assertNotSame(State.STARTING, service.state());
}

代码示例来源:origin: google/guava

/** @since 15.0 */
@Override
public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException {
 delegate.awaitTerminated(timeout, unit);
}

代码示例来源:origin: google/guava

WeakReference<ServiceManagerState> stateReference = new WeakReference<>(state);
for (Service service : copy) {
 service.addListener(new ServiceListener(service, stateReference), directExecutor());
 checkArgument(service.state() == NEW, "Can only manage NEW services, %s", service);

代码示例来源:origin: co.cask.cdap/cdap-app-fabric

private void stopQuietly(Service service) {
 try {
  service.stopAndWait();
 } catch (Exception e) {
  LOG.debug("Error stopping the preview runner.", e);
 }
}

代码示例来源:origin: google/guava

/** @since 14.0 */
@Override
public final Throwable failureCause() {
 return delegate.failureCause();
}

代码示例来源:origin: google/guava

@Override
public final boolean isRunning() {
 return delegate.isRunning();
}

代码示例来源:origin: org.kill-bill.billing/killbill-osgi-bundles-jruby

@Deprecated
@Override 
 public final State startAndWait() {
 return delegate.startAndWait();
}

代码示例来源:origin: apache/incubator-gobblin

@Override
 public void failure(Service service) {
  super.failure(service);
  LOG.error(String.format("Service %s has failed.", service.getClass().getSimpleName()), service.failureCause());
  try {
   service.stopAsync();
   ServiceBasedAppLauncher.this.stop();
  } catch (ApplicationException ae) {
   LOG.error("Could not shutdown services gracefully. This may cause the application to hang.");
  }
 }
});

代码示例来源:origin: co.cask.cdap/cdap-app-fabric

@Override
protected void doStop() throws Exception {
 if (service.state() != Service.State.TERMINATED && service.state() != Service.State.FAILED) {
  LOG.debug("stopping controller service for program {}.", getProgramRunId());
  service.stopAndWait();
  LOG.debug("stopped controller service for program {}, waiting for it to finish running listener hooks.",
       getProgramRunId());
  serviceStoppedLatch.await(30, TimeUnit.SECONDS);
  LOG.debug("controller service for program {} finished running listener hooks.", getProgramRunId());
 }
}

相关文章