List of usage examples for com.google.common.util.concurrent MoreExecutors listeningDecorator
@GwtIncompatible("TODO") public static ListeningScheduledExecutorService listeningDecorator(ScheduledExecutorService delegate)
From source file:org.opendaylight.unimgr.mef.nrp.impl.commonservice.TapiCommonServiceImpl.java
public void init() { Objects.requireNonNull(broker); if (executor == null) { executor = MoreExecutors.listeningDecorator( new ThreadPoolExecutor(4, 16, 30, TimeUnit.MINUTES, new LinkedBlockingQueue<>())); }//from www .j a v a 2 s.c o m LOG.info("TapiCommonServiceImpl initialized"); }
From source file:com.github.jsdossier.RenderTaskExecutor.java
@Inject RenderTaskExecutor(@NumThreads int numThreads, DossierFileSystem dfs, RenderDocumentationTaskSupplierFactory documentationTaskSupplierFactory, RenderResourceTaskFactory resourceTaskFactory, RenderMarkdownTaskFactory markdownTaskFactory, RenderSourceFileTaskFactory sourceFileTaskFactory, RenderIndexTask indexTask, RenderTypeIndexTask typeIndexTask) { this.dfs = dfs; this.documentationTaskSupplierFactory = documentationTaskSupplierFactory; this.resourceTaskFactory = resourceTaskFactory; this.markdownTaskFactory = markdownTaskFactory; this.sourceFileTaskFactory = sourceFileTaskFactory; this.indexTask = indexTask; this.typeIndexTask = typeIndexTask; this.executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(numThreads)); }
From source file:co.cask.cdap.internal.app.runtime.schedule.TimeScheduler.java
void init() throws SchedulerException { try {/*w w w. j a v a 2 s.c o m*/ taskExecutorService = MoreExecutors.listeningDecorator( Executors.newCachedThreadPool(Threads.createDaemonThreadFactory("time-schedule-task"))); scheduler = schedulerSupplier.get(); scheduler.setJobFactory(createJobFactory(store)); } catch (org.quartz.SchedulerException e) { throw new SchedulerException(e); } }
From source file:org.codice.ddf.catalog.migratable.impl.MigrationTaskManager.java
/** * The creation of a task manager requires the passing of migratable configurations so that * task behavior can be explicitly defined (i.e. where to export, how many metacards per file, * and other useful data). Also initializes the {@link MigrationFileWriter} and threading services. * * @param config Configuration object to use for customizing catalog migration process. *///from ww w .j av a2 s.com public MigrationTaskManager(@NotNull final CatalogMigratableConfig config, @NotNull final MigrationFileWriter fileWriter) { notNull(config, "Configuration object cannot be null"); notNull(fileWriter, "File writer cannot be null"); this.executorSupplier = this::createExecutorService; this.catalogConfig = config; this.fileWriter = fileWriter; this.failureFlag = false; this.taskExecutor = MoreExecutors.listeningDecorator(executorSupplier.get()); }
From source file:org.apache.hive.ptest.execution.AbstractTestPhase.java
public void initialize(String name) throws Exception { baseDir = createBaseDir(name);/* w w w. j av a 2 s . c o m*/ logDir = Dirs.create(new File(baseDir, "logs")); scratchDir = Dirs.create(new File(baseDir, "scratch")); succeededLogDir = Dirs.create(new File(logDir, "succeeded")); failedLogDir = Dirs.create(new File(logDir, "failed")); executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2)); executionContext = mock(ExecutionContext.class); hostExecutorBuilder = mock(HostExecutorBuilder.class); localCommandFactory = new MockLocalCommandFactory(LOG); localCommand = mock(LocalCommand.class); localCommandFactory.setInstance(localCommand); sshCommandExecutor = spy(new MockSSHCommandExecutor(LOG)); rsyncCommandExecutor = spy(new MockRSyncCommandExecutor(LOG)); logger = new TestLogger(System.err, TestLogger.LEVEL.TRACE); templateDefaults = ImmutableMap.<String, String>builder().put("localDir", LOCAL_DIR) .put("workingDir", WORKING_DIR).put("instanceName", INSTANCE_NAME).put("branch", BRANCH) .put("logDir", logDir.getAbsolutePath()).put("repository", REPOSITORY) .put("repositoryName", REPOSITORY_NAME).build(); host = new Host(HOST, USER, new String[] { LOCAL_DIR }, 2); }
From source file:org.gradle.internal.filewatch.FileSystemChangeWaiter.java
@Override public void execute(FileSystemSubset taskFileSystemInputs, Runnable notifier) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); final StoppableExecutor executorService = executorFactory.create("quiet period waiter"); FileWatcher watcher = fileWatcherFactory.watch(taskFileSystemInputs, new Action<Throwable>() { @Override//from w w w .j ava 2 s. com public void execute(Throwable throwable) { error.set(throwable); latch.countDown(); } }, new FileWatcherListener() { private IdleTimeout timeout; @Override public void onChange(final FileWatcher watcher, FileWatcherEvent event) { if (timeout == null) { timeout = new IdleTimeout(QUIET_PERIOD, new Runnable() { @Override public void run() { watcher.stop(); latch.countDown(); } }); executorService.execute(new Runnable() { @Override public void run() { timeout.await(); } }); } timeout.tick(); } }); final StoppableExecutor keyboardHandlerExecutor = executorFactory .create("Continuous building keyboard handler"); ListenableFuture<Boolean> keyboardHandlerFuture = submitAsyncKeyboardHandler( MoreExecutors.listeningDecorator(keyboardHandlerExecutor), latch); try { notifier.run(); latch.await(); Throwable throwable = error.get(); if (throwable != null) { throw UncheckedException.throwAsUncheckedException(throwable); } } catch (Exception e) { throw UncheckedException.throwAsUncheckedException(e); } finally { if (!keyboardHandlerFuture.isDone()) { keyboardHandlerFuture.cancel(true); } else if (Futures.getUnchecked(keyboardHandlerFuture)) { cancellationRequested.set(true); } CompositeStoppable.stoppable(watcher, executorService, keyboardHandlerExecutor).stop(); } }
From source file:org.anhonesteffort.p25.P25DcodrApplication.java
@Override public void run(P25DcodrConfig config, Environment environment) throws Exception { P25DcodrMetrics.init(config.getCloudWatch(), new MetricRegistry()); EventLoopGroup nettyPool = new NioEventLoopGroup(); ListeningExecutorService dspPool = MoreExecutors .listeningDecorator(Executors.newFixedThreadPool(config.getDspPoolSize())); ExecutorService kinesisPool = Executors.newFixedThreadPool(config.getKinesis().getSenderPoolSize()); Client jerseyClient = buildClient(config, environment); String serverUri = getServerUri(config); WebTarget qualifyTarget = jerseyClient.target(serverUri).path("qualify"); WebTarget followTarget = jerseyClient.target(serverUri).path("channels/control"); WebTarget trafficTarget = jerseyClient.target(serverUri).path("channels/traffic/group"); ChnlzrConnectionFactory chnlzrConnections = new ChnlzrConnectionFactory(chnlzrConfig, NioSocketChannel.class, nettyPool); HostId chnlzrHost = new HostId(config.getChnlzrHostname(), config.getChnlzrPort()); ChnlzrController chnlzr = new ChnlzrController(chnlzrHost, chnlzrConnections); ChannelMonitor channelMonitor = new RetryingControlChannelMonitor(config, qualifyTarget, followTarget); KinesisClientFactory kinesisClients = new KinesisClientFactory(config.getKinesis(), kinesisPool); KinesisRecordProducerFactory kinesisSenders = new KinesisRecordProducerFactory(config.getKinesis(), kinesisClients);/*from w w w .j a va 2 s.c om*/ environment.healthChecks().register("dumb", new DumbCheck()); environment.jersey().register(new ControlChannelQualifyingResource(config, chnlzr, dspPool)); environment.jersey().register(new ControlChannelFollowingResource(config, chnlzr, channelMonitor, kinesisSenders, trafficTarget, dspPool)); environment.jersey().register( new TrafficChannelCaptureResource(config, chnlzr, channelMonitor, kinesisSenders, dspPool)); }
From source file:org.eclipse.che.plugin.internal.installer.PluginInstallerImpl.java
/** * Setup a new installer based on the given configuration * @param pluginConfiguration that will be used to find ChE_HOME or install script *//*from w ww . j a va2 s. co m*/ @Inject public PluginInstallerImpl(PluginConfiguration pluginConfiguration) { this.currentExecution = new AtomicReference<>(); this.pluginConfiguration = pluginConfiguration; ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(2, new ThreadFactoryBuilder() .setNameFormat(PluginInstallerImpl.class.getSimpleName() + "-[%d]").setDaemon(true).build()); // decorate this executor to allow callback/listener this.executor = MoreExecutors.listeningDecorator(threadPoolExecutor); this.executions = new ConcurrentHashMap<>(); }
From source file:io.druid.query.groupby.GroupByQueryRunnerFactory.java
@Override public QueryRunner<Row> mergeRunners(final ExecutorService exec, Iterable<QueryRunner<Row>> queryRunners) { // mergeRunners should take ListeningExecutorService at some point final ListeningExecutorService queryExecutor = MoreExecutors.listeningDecorator(exec); if (config.get().isSingleThreaded()) { return new ConcatQueryRunner<>(Sequences.map(Sequences.simple(queryRunners), new Function<QueryRunner<Row>, QueryRunner<Row>>() { @Override/* w w w.j av a 2s . co m*/ public QueryRunner<Row> apply(final QueryRunner<Row> input) { return new QueryRunner<Row>() { @Override public Sequence<Row> run(final Query<Row> query, final Map<String, Object> responseContext) { final GroupByQuery queryParam = (GroupByQuery) query; final Pair<IncrementalIndex, Accumulator<IncrementalIndex, Row>> indexAccumulatorPair = GroupByQueryHelper .createIndexAccumulatorPair(queryParam, config.get(), computationBufferPool); final Pair<Queue, Accumulator<Queue, Row>> bySegmentAccumulatorPair = GroupByQueryHelper .createBySegmentAccumulatorPair(); final int priority = query.getContextPriority(0); final boolean bySegment = query.getContextBySegment(false); final ListenableFuture<Void> future = queryExecutor .submit(new AbstractPrioritizedCallable<Void>(priority) { @Override public Void call() throws Exception { if (bySegment) { input.run(queryParam, responseContext).accumulate( bySegmentAccumulatorPair.lhs, bySegmentAccumulatorPair.rhs); } else { input.run(query, responseContext).accumulate( indexAccumulatorPair.lhs, indexAccumulatorPair.rhs); } return null; } }); try { queryWatcher.registerQuery(query, future); final Number timeout = query.getContextValue(QueryContextKeys.TIMEOUT, (Number) null); if (timeout == null) { future.get(); } else { future.get(timeout.longValue(), TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { log.warn(e, "Query interrupted, cancelling pending results, query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException("Query interrupted"); } catch (CancellationException e) { throw new QueryInterruptedException("Query cancelled"); } catch (TimeoutException e) { log.info("Query timeout, cancelling pending results for query id [%s]", query.getId()); future.cancel(true); throw new QueryInterruptedException("Query timeout"); } catch (ExecutionException e) { throw Throwables.propagate(e.getCause()); } if (bySegment) { return Sequences.simple(bySegmentAccumulatorPair.lhs); } return Sequences .simple(indexAccumulatorPair.lhs.iterableWithPostAggregations(null)); } }; } })); } else { return new GroupByParallelQueryRunner(queryExecutor, config, queryWatcher, computationBufferPool, queryRunners); } }
From source file:com.android.tools.idea.apk.viewer.dex.DexFileViewer.java
public DexFileViewer(@NotNull VirtualFile dexFile) { //noinspection Convert2Lambda // we need a new instance of this disposable every time, not just a lambda method myDisposable = new Disposable() { @Override//from ww w.j a va 2 s . c o m public void dispose() { } }; myLoadingPanel = new JBLoadingPanel(new BorderLayout(), myDisposable); myLoadingPanel.startLoading(); DefaultTreeModel treeModel = new DefaultTreeModel(new LoadingNode()); myTree = new Tree(treeModel); myTree.setRootVisible(true); myTree.setShowsRootHandles(true); new TreeSpeedSearch(myTree, path -> { Object o = path.getLastPathComponent(); if (!(o instanceof PackageTreeNode)) { return ""; } PackageTreeNode node = (PackageTreeNode) o; return node.getName(); }); ColumnTreeBuilder builder = new ColumnTreeBuilder(myTree) .addColumn(new ColumnTreeBuilder.ColumnBuilder().setName("Class").setPreferredWidth(500) .setHeaderAlignment(SwingConstants.LEFT).setRenderer(new PackageTreeNodeRenderer())) .addColumn(new ColumnTreeBuilder.ColumnBuilder().setName("Defined Methods").setPreferredWidth(100) .setHeaderAlignment(SwingConstants.LEFT).setRenderer(new MethodCountRenderer(true))) .addColumn(new ColumnTreeBuilder.ColumnBuilder().setName("Referenced Methods") .setPreferredWidth(100).setHeaderAlignment(SwingConstants.LEFT) .setRenderer(new MethodCountRenderer(false))); JComponent columnTree = builder.build(); myLoadingPanel.add(columnTree, BorderLayout.CENTER); DexParser dexParser = new DexParser(MoreExecutors.listeningDecorator(PooledThreadExecutor.INSTANCE), dexFile); ListenableFuture<PackageTreeNode> future = dexParser.constructMethodRefCountTree(); Futures.addCallback(future, new FutureCallback<PackageTreeNode>() { @Override public void onSuccess(PackageTreeNode result) { myTree.setModel(new DefaultTreeModel(result)); myTree.setRootVisible(false); myLoadingPanel.stopLoading(); } @Override public void onFailure(Throwable t) { } }, EdtExecutor.INSTANCE); SimpleColoredComponent titleComponent = new SimpleColoredComponent(); Futures.addCallback(dexParser.getDexFileStats(), new FutureCallback<DexParser.DexFileStats>() { @Override public void onSuccess(DexParser.DexFileStats result) { titleComponent.setIcon(AllIcons.General.Information); titleComponent.append("This dex file defines "); titleComponent.append(Integer.toString(result.classCount), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); titleComponent.append(" classes with "); titleComponent.append(Integer.toString(result.definedMethodCount), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); titleComponent.append(" methods, and references "); titleComponent.append(Integer.toString(result.referencedMethodCount), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); titleComponent.append(" methods."); } @Override public void onFailure(Throwable t) { } }); myLoadingPanel.add(titleComponent, BorderLayout.NORTH); }