本文整理汇总了Java中com.google.common.util.concurrent.Service类的典型用法代码示例。如果您正苦于以下问题:Java Service类的具体用法?Java Service怎么用?Java Service使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Service类属于com.google.common.util.concurrent包,在下文中一共展示了Service类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: execute
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
/**
*
* @param callbacks
*/
@Override
public void execute(CoinActionCallback<CurrencyCoin>... callbacks) {
_callbacks = callbacks;
// reinitWallet();
final DeterministicSeed seed = createDeterministicSeed();
_bitcoinManager.getCurrencyCoin().getWalletManager().addListener(new Service.Listener() {
@Override
public void terminated(Service.State from) {
super.terminated(from);
WalletAppKit appKit = setupWallet();
appKit.setDownloadListener(BitcoinRecoverAction.this)
.setBlockingStartup(false)
.setUserAgent(ServiceConsts.SERVICE_APP_NAME, "0.1")
.restoreWalletFromSeed(seed);
_bitcoinManager.getCurrencyCoin().setWalletManager(appKit);
_bitcoinManager.getCurrencyCoin().getWalletManager().startAsync();
}
}, Executors.newSingleThreadExecutor());
_bitcoinManager.getCurrencyCoin().getWalletManager().stopAsync();
}
示例2: main
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
public static void main(String... args) throws Exception {
PropertyConfigurator.configure("D:/log4j.properties");
try {
List<Replica> members = Lists.newArrayList();
members.add(Replica.fromString("localhost:10001"));
members.add(Replica.fromString("localhost:10002"));
File logDir = new File("D:/raft");
logDir.mkdir();
// configure the service
RaftService raft = RaftService.newBuilder().local(Replica.fromString("localhost:10000")).members(members).logDir(logDir).timeout(300).build(new Test());
// start this replica
Service guavaservice = raft.startAsync();
guavaservice.awaitRunning();
// let's commit some things
// for (int i = 0; i < 10; i++) {
// raft.commit(new byte[] { 'O', '_', 'o' });
// }
} catch (Exception e) {
e.printStackTrace();
}
}
示例3: module
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
public static Module module(final int configSourcePriority)
{
return new AbstractModule()
{
@Override
protected void configure()
{
MapBinder<Integer, DynamicConfigSource> mapBinder = MapBinder.newMapBinder(binder(), Integer.class, DynamicConfigSource.class);
mapBinder.addBinding(configSourcePriority).to(FileDynamicConfigSource.class);
bind(FileDynamicConfigSource.class);
// Bind inner class as a service to ensure resource cleanup
Multibinder.newSetBinder(binder(), Service.class).addBinding().to(FileDynamicConfigSourceService.class);
}
};
}
示例4: testCronSchedulerLifecycle
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
@Test
public void testCronSchedulerLifecycle() throws Exception {
control.replay();
Scheduler scheduler = injector.getInstance(Scheduler.class);
assertFalse(scheduler.isStarted());
Service cronLifecycle = boot();
assertTrue(cronLifecycle.isRunning());
assertTrue(scheduler.isStarted());
cronLifecycle.stopAsync().awaitTerminated();
assertFalse(cronLifecycle.isRunning());
assertTrue(scheduler.isShutdown());
}
示例5: testJobsAreScheduled
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
@Test
public void testJobsAreScheduled() throws Exception {
auroraCronJob.execute(isA(JobExecutionContext.class));
control.replay();
final Scheduler scheduler = injector.getInstance(Scheduler.class);
storage.write((NoResult.Quiet)
storeProvider -> storeProvider.getCronJobStore().saveAcceptedJob(CRON_JOB));
final CountDownLatch cronRan = new CountDownLatch(1);
scheduler.getListenerManager().addTriggerListener(new CountDownWhenComplete(cronRan));
Service service = boot();
cronRan.await();
service.stopAsync().awaitTerminated();
}
示例6: testBindings
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
@Test
public void testBindings() throws Exception {
Injector injector = createInjector(new AsyncModule());
control.replay();
Set<Service> services = injector.getInstance(
Key.get(new TypeLiteral<Set<Service>>() { }, AppStartup.class));
for (Service service : services) {
service.startAsync().awaitRunning();
}
injector.getBindings();
assertEquals(
ImmutableMap.of(
RegisterGauges.TIMEOUT_QUEUE_GAUGE, 0,
RegisterGauges.ASYNC_TASKS_GAUGE, 0L,
RegisterGauges.DELAY_QUEUE_GAUGE, 0),
statsProvider.getAllValues()
);
}
示例7: testShutdownStopAndRunException
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
/**
* Tests the behavior of AbstractThreadPoolService during shutdown when both a StopException and a RunException are present.
*/
@Test
public void testShutdownStopAndRunException() {
val s = newService();
// Stop it and verify it hasn't shut down - it should still be waiting on the runFuture.
val stopException = new IntentionalException("stop");
s.errorHandler(stopException);
val runException = new IntentionalException("run");
s.runFuture.completeExceptionally(runException);
AssertExtensions.assertThrows(
"Service did not fail.",
() -> s.awaitTerminated(),
ex -> ex instanceof IllegalStateException);
Assert.assertEquals("Unexpected state upon failed shutdown.", Service.State.FAILED, s.state());
Assert.assertEquals("Unexpected failure cause.", stopException, s.failureCause());
Assert.assertEquals("Unexpected suppressed exception.", runException, s.failureCause().getSuppressed()[0]);
}
示例8: startUp
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
@Override
protected void startUp() throws Exception {
Throwable failureCause = null;
for (Service service : services) {
try {
service.startAndWait();
} catch (UncheckedExecutionException e) {
failureCause = e.getCause();
break;
}
}
if (failureCause != null) {
// Stop all running services and then throw the failure exception
try {
stopAll();
} catch (Throwable t) {
// Ignore the stop error. Just log.
LOG.warn("Failed when stopping all services on start failure", t);
}
Throwables.propagateIfPossible(failureCause, Exception.class);
throw new RuntimeException(failureCause);
}
}
示例9: testShutdownNoFailure
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
/**
* Tests the behavior of AbstractThreadPoolService when a normal shutdown (no errors) happens.
*/
@Test
public void testShutdownNoFailure() {
@Cleanup
val s = newService();
// Stop it and verify it hasn't shut down - it should still be waiting on the runFuture.
s.stopAsync();
AssertExtensions.assertThrows(
"Service stopped even though the runFuture did not complete.",
() -> s.awaitTerminated(SHORT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS),
ex -> ex instanceof TimeoutException);
Assert.assertEquals("Unexpected state while shutting down.", Service.State.STOPPING, s.state());
// Complete the future and await normal termination.
s.runFuture.complete(null);
s.awaitTerminated();
Assert.assertEquals("Unexpected state upon normal shutdown.", Service.State.TERMINATED, s.state());
}
示例10: running
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
@Override
public void running() {
if (hasCalled(Service.State.RUNNING)) {
return;
}
executor.execute(new Runnable() {
@Override
public void run() {
try {
delegate.running();
} catch (Throwable t) {
LOG.warn("Exception thrown from listener", t);
}
}
});
}
示例11: stopping
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
@Override
public void stopping(final Service.State from) {
if (hasCalled(Service.State.STOPPING)) {
return;
}
executor.execute(new Runnable() {
@Override
public void run() {
try {
delegate.stopping(from);
} catch (Throwable t) {
LOG.warn("Exception thrown from listener", t);
}
}
});
}
示例12: terminated
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
@Override
public void terminated(final Service.State from) {
if (hasCalled(Service.State.TERMINATED)) {
return;
}
executor.execute(new Runnable() {
@Override
public void run() {
try {
delegate.terminated(from);
} catch (Throwable t) {
LOG.warn("Exception thrown from listener", t);
}
}
});
}
示例13: createService
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
private Service createService(ZKClient zkClient, RunId runId) {
return new AbstractTwillService(zkClient, runId) {
private final CountDownLatch stopLatch = new CountDownLatch(1);
@Override
protected void doStart() throws Exception {
LOG.info("Start");
}
@Override
protected void doRun() throws Exception {
stopLatch.await();
}
@Override
protected void doStop() throws Exception {
LOG.info("Stop");
}
@Override
protected void triggerShutdown() {
stopLatch.countDown();
}
};
}
示例14: testCompletion
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
@Test
public void testCompletion() throws ExecutionException, InterruptedException {
Service service = new DummyService("s1", new AtomicBoolean());
ListenableFuture<Service.State> completion = Services.getCompletionFuture(service);
service.start();
service.stop();
completion.get();
AtomicBoolean transiting = new AtomicBoolean();
service = new DummyService("s2", transiting);
completion = Services.getCompletionFuture(service);
service.startAndWait();
transiting.set(true);
service.stop();
try {
completion.get();
Assert.assertTrue(false);
} catch (ExecutionException e) {
// Expected
}
}
示例15: onStop
import com.google.common.util.concurrent.Service; //导入依赖的package包/类
/**
* Attaches the given callbacks which will be invoked when the given Service enters a TERMINATED or FAILED state.
* The callbacks are optional and may be invoked synchronously if the Service is already in one of these states.
*
* @param service The Service to attach to.
* @param terminatedCallback (Optional) A Runnable that will be invoked if the Service enters a TERMINATED state.
* @param failureCallback (Optional) A Runnable that will be invoked if the Service enters a FAILED state.
* @param executor An Executor to use for callback invocations.
*/
public static void onStop(Service service, Runnable terminatedCallback, Consumer<Throwable> failureCallback, Executor executor) {
ShutdownListener listener = new ShutdownListener(terminatedCallback, failureCallback);
service.addListener(listener, executor);
// addListener() will not invoke the callbacks if the service is already in a terminal state. As such, we need to
// manually check for these states after registering the listener and invoke the appropriate callback. The
// ShutdownListener will make sure they are not invoked multiple times.
Service.State state = service.state();
if (state == Service.State.FAILED) {
// We don't care (or know) the state from which we came, so we just pass some random one.
listener.failed(Service.State.FAILED, service.failureCause());
} else if (state == Service.State.TERMINATED) {
listener.terminated(Service.State.TERMINATED);
}
}