List of usage examples for com.google.common.util.concurrent MoreExecutors sameThreadExecutor
@Deprecated @GwtIncompatible("TODO") public static ListeningExecutorService sameThreadExecutor()
From source file:io.xpydev.paycoinj.kits.WalletAppKit.java
@Override protected void startUp() throws Exception { // Runs in a separate thread. if (!directory.exists()) { if (!directory.mkdirs()) { throw new IOException("Could not create directory " + directory.getAbsolutePath()); }//from www.jav a 2s. c o m } log.info("Starting up with directory = {}", directory); try { File chainFile = new File(directory, filePrefix + ".spvchain"); File validHashFile = new File(directory, filePrefix + ".hashes"); boolean chainFileExists = chainFile.exists(); vWalletFile = new File(directory, filePrefix + ".wallet"); boolean shouldReplayWallet = (vWalletFile.exists() && !chainFileExists) || restoreFromSeed != null; vWallet = createOrLoadWallet(shouldReplayWallet); validHashStore = new ValidHashStore(validHashFile); vStore = new SPVBlockStore(params, chainFile); if ((!chainFileExists || restoreFromSeed != null) && checkpoints != null) { // Initialize the chain file with a checkpoint to speed up first-run sync. long time; if (restoreFromSeed != null) { time = restoreFromSeed.getCreationTimeSeconds(); if (chainFileExists) { log.info("Deleting the chain file in preparation from restore."); vStore.close(); if (!chainFile.delete()) throw new Exception("Failed to delete chain file in preparation for restore."); vStore = new SPVBlockStore(params, chainFile); } } else { time = vWallet.getEarliestKeyCreationTime(); } CheckpointManager.checkpoint(params, checkpoints, vStore, time); } vChain = new BlockChain(params, vStore, validHashStore); vPeerGroup = createPeerGroup(); if (this.userAgent != null) vPeerGroup.setUserAgent(userAgent, version); // Set up peer addresses or discovery first, so if wallet extensions try to broadcast a transaction // before we're actually connected the broadcast waits for an appropriate number of connections. if (peerAddresses != null) { log.info("no peer addressed found"); for (PeerAddress addr : peerAddresses) vPeerGroup.addAddress(addr); vPeerGroup.setMaxConnections(peerAddresses.length); peerAddresses = null; } else { log.info("starting peer discovery"); vPeerGroup.addPeerDiscovery(new DnsDiscovery(params)); } vChain.addWallet(vWallet); vPeerGroup.addWallet(vWallet); onSetupCompleted(); if (blockingStartup) { vPeerGroup.startAsync(); vPeerGroup.awaitRunning(); // Make sure we shut down cleanly. installShutdownHook(); completeExtensionInitiations(vPeerGroup); // TODO: Be able to use the provided download listener when doing a blocking startup. final DownloadListener listener = new DownloadListener(); log.info("blockchain download starting"); vPeerGroup.startBlockChainDownload(listener); listener.await(); } else { vPeerGroup.startAsync(); vPeerGroup.addListener(new Service.Listener() { @Override public void running() { completeExtensionInitiations(vPeerGroup); final PeerEventListener l = downloadListener == null ? new DownloadListener() : downloadListener; log.info("blockchain download starting"); vPeerGroup.startBlockChainDownload(l); } @Override public void failed(State from, Throwable failure) { throw new RuntimeException(failure); } }, MoreExecutors.sameThreadExecutor()); } } catch (BlockStoreException e) { throw new IOException(e); } }
From source file:org.opennms.features.vaadin.surveillanceviews.ui.dashboard.SurveillanceViewGraphComponent.java
/** * {@inheritDoc}// w w w . j a v a2 s .co m */ @Override public void refreshDetails(final Set<OnmsCategory> rowCategories, final Set<OnmsCategory> colCategories) { if (m_future != null && !m_future.isDone()) { return; } m_nodeSelect.setEnabled(false); m_resourceSelect.setEnabled(false); m_graphSelect.setEnabled(false); m_future = getSurveillanceViewService().getExecutorService().submit(new Callable<List<OnmsNode>>() { @Override public List<OnmsNode> call() throws Exception { /** * retrieve the matching nodes */ return getSurveillanceViewService().getNodesForCategories(rowCategories, colCategories); } }); m_future.addListener(new Runnable() { @Override public void run() { try { final List<OnmsNode> nodes = m_future.get(); getUI().access(new Runnable() { @Override public void run() { /** * save the current selection */ Integer selectedNodeId = (Integer) m_nodeSelect.getValue(); String selectedResourceId = (String) m_resourceSelect.getValue(); String selectedGraph = (String) m_graphSelect.getValue(); LOG.debug("Saved selection={} / {} / {}", selectedNodeId == null ? "null" : selectedNodeId, selectedResourceId == null ? "null" : selectedResourceId, selectedGraph); /** * remove all entries in the node selection box */ m_nodeSelect.removeAllItems(); /** * add the new items */ if (nodes != null && !nodes.isEmpty()) { for (OnmsNode node : nodes) { m_nodeSelect.addItem(node.getId()); m_nodeSelect.setItemCaption(node.getId(), "Node: " + node.getLabel()); } } m_nodeSelect.setEnabled(true); m_resourceSelect.setEnabled(true); m_graphSelect.setEnabled(true); /** * try to select the same node/resource/graph combination as before */ if (selectedNodeId != null) { for (Integer onmsNodeId : (Collection<Integer>) m_nodeSelect.getItemIds()) { if (onmsNodeId.equals(selectedNodeId)) { m_nodeSelect.select(onmsNodeId); if (selectedResourceId != null) { for (String onmsResourceId : (Collection<String>) m_resourceSelect .getItemIds()) { if (onmsResourceId.equals(selectedResourceId)) { m_resourceSelect.select(onmsResourceId); if (selectedGraph != null) { m_graphSelect.select(selectedGraph); } } } } return; } } } /** * if nothing was selected before, just select the first entry if possible */ Iterator<?> i = m_nodeSelect.getItemIds().iterator(); if (i.hasNext()) { m_nodeSelect.select(i.next()); } } }); } catch (InterruptedException e) { LOG.error("Interrupted", e); } catch (ExecutionException e) { LOG.error("Exception in task", e.getCause()); } } }, MoreExecutors.sameThreadExecutor()); }
From source file:org.elasticsearch.threadpool.ThreadPool.java
private ExecutorHolder rebuild(String name, ExecutorHolder previousExecutorHolder, @Nullable Settings settings, Settings defaultSettings) {/*from ww w. ja va2 s . c om*/ if (Names.SAME.equals(name)) { // Don't allow to change the "same" thread executor return previousExecutorHolder; } if (settings == null) { settings = ImmutableSettings.Builder.EMPTY_SETTINGS; } Info previousInfo = previousExecutorHolder != null ? previousExecutorHolder.info : null; String type = settings.get("type", previousInfo != null ? previousInfo.getType() : defaultSettings.get("type")); ThreadFactory threadFactory = EsExecutors.daemonThreadFactory(this.settings, name); if ("same".equals(type)) { if (previousExecutorHolder != null) { logger.debug("updating thread_pool [{}], type [{}]", name, type); } else { logger.debug("creating thread_pool [{}], type [{}]", name, type); } return new ExecutorHolder(MoreExecutors.sameThreadExecutor(), new Info(name, type)); } else if ("cached".equals(type)) { TimeValue defaultKeepAlive = defaultSettings.getAsTime("keep_alive", timeValueMinutes(5)); if (previousExecutorHolder != null) { if ("cached".equals(previousInfo.getType())) { TimeValue updatedKeepAlive = settings.getAsTime("keep_alive", previousInfo.getKeepAlive()); if (!previousInfo.getKeepAlive().equals(updatedKeepAlive)) { logger.debug("updating thread_pool [{}], type [{}], keep_alive [{}]", name, type, updatedKeepAlive); ((EsThreadPoolExecutor) previousExecutorHolder.executor) .setKeepAliveTime(updatedKeepAlive.millis(), TimeUnit.MILLISECONDS); return new ExecutorHolder(previousExecutorHolder.executor, new Info(name, type, -1, -1, updatedKeepAlive, null)); } return previousExecutorHolder; } if (previousInfo.getKeepAlive() != null) { defaultKeepAlive = previousInfo.getKeepAlive(); } } TimeValue keepAlive = settings.getAsTime("keep_alive", defaultKeepAlive); if (previousExecutorHolder != null) { logger.debug("updating thread_pool [{}], type [{}], keep_alive [{}]", name, type, keepAlive); } else { logger.debug("creating thread_pool [{}], type [{}], keep_alive [{}]", name, type, keepAlive); } Executor executor = EsExecutors.newCached(keepAlive.millis(), TimeUnit.MILLISECONDS, threadFactory); return new ExecutorHolder(executor, new Info(name, type, -1, -1, keepAlive, null)); } else if ("fixed".equals(type)) { int defaultSize = defaultSettings.getAsInt("size", EsExecutors.boundedNumberOfProcessors(settings)); SizeValue defaultQueueSize = defaultSettings.getAsSize("queue", defaultSettings.getAsSize("queue_size", null)); if (previousExecutorHolder != null) { if ("fixed".equals(previousInfo.getType())) { SizeValue updatedQueueSize = settings.getAsSize("capacity", settings.getAsSize("queue", settings.getAsSize("queue_size", previousInfo.getQueueSize()))); if (Objects.equal(previousInfo.getQueueSize(), updatedQueueSize)) { int updatedSize = settings.getAsInt("size", previousInfo.getMax()); if (previousInfo.getMax() != updatedSize) { logger.debug("updating thread_pool [{}], type [{}], size [{}], queue_size [{}]", name, type, updatedSize, updatedQueueSize); ((EsThreadPoolExecutor) previousExecutorHolder.executor).setCorePoolSize(updatedSize); ((EsThreadPoolExecutor) previousExecutorHolder.executor) .setMaximumPoolSize(updatedSize); return new ExecutorHolder(previousExecutorHolder.executor, new Info(name, type, updatedSize, updatedSize, null, updatedQueueSize)); } return previousExecutorHolder; } } if (previousInfo.getMax() >= 0) { defaultSize = previousInfo.getMax(); } defaultQueueSize = previousInfo.getQueueSize(); } int size = settings.getAsInt("size", defaultSize); SizeValue queueSize = settings.getAsSize("capacity", settings.getAsSize("queue", settings.getAsSize("queue_size", defaultQueueSize))); logger.debug("creating thread_pool [{}], type [{}], size [{}], queue_size [{}]", name, type, size, queueSize); Executor executor = EsExecutors.newFixed(size, queueSize == null ? -1 : (int) queueSize.singles(), threadFactory); return new ExecutorHolder(executor, new Info(name, type, size, size, null, queueSize)); } else if ("scaling".equals(type)) { TimeValue defaultKeepAlive = defaultSettings.getAsTime("keep_alive", timeValueMinutes(5)); int defaultMin = defaultSettings.getAsInt("min", 1); int defaultSize = defaultSettings.getAsInt("size", EsExecutors.boundedNumberOfProcessors(settings)); if (previousExecutorHolder != null) { if ("scaling".equals(previousInfo.getType())) { TimeValue updatedKeepAlive = settings.getAsTime("keep_alive", previousInfo.getKeepAlive()); int updatedMin = settings.getAsInt("min", previousInfo.getMin()); int updatedSize = settings.getAsInt("max", settings.getAsInt("size", previousInfo.getMax())); if (!previousInfo.getKeepAlive().equals(updatedKeepAlive) || previousInfo.getMin() != updatedMin || previousInfo.getMax() != updatedSize) { logger.debug("updating thread_pool [{}], type [{}], keep_alive [{}]", name, type, updatedKeepAlive); if (!previousInfo.getKeepAlive().equals(updatedKeepAlive)) { ((EsThreadPoolExecutor) previousExecutorHolder.executor) .setKeepAliveTime(updatedKeepAlive.millis(), TimeUnit.MILLISECONDS); } if (previousInfo.getMin() != updatedMin) { ((EsThreadPoolExecutor) previousExecutorHolder.executor).setCorePoolSize(updatedMin); } if (previousInfo.getMax() != updatedSize) { ((EsThreadPoolExecutor) previousExecutorHolder.executor) .setMaximumPoolSize(updatedSize); } return new ExecutorHolder(previousExecutorHolder.executor, new Info(name, type, updatedMin, updatedSize, updatedKeepAlive, null)); } return previousExecutorHolder; } if (previousInfo.getKeepAlive() != null) { defaultKeepAlive = previousInfo.getKeepAlive(); } if (previousInfo.getMin() >= 0) { defaultMin = previousInfo.getMin(); } if (previousInfo.getMax() >= 0) { defaultSize = previousInfo.getMax(); } } TimeValue keepAlive = settings.getAsTime("keep_alive", defaultKeepAlive); int min = settings.getAsInt("min", defaultMin); int size = settings.getAsInt("max", settings.getAsInt("size", defaultSize)); if (previousExecutorHolder != null) { logger.debug("updating thread_pool [{}], type [{}], min [{}], size [{}], keep_alive [{}]", name, type, min, size, keepAlive); } else { logger.debug("creating thread_pool [{}], type [{}], min [{}], size [{}], keep_alive [{}]", name, type, min, size, keepAlive); } Executor executor = EsExecutors.newScaling(min, size, keepAlive.millis(), TimeUnit.MILLISECONDS, threadFactory); return new ExecutorHolder(executor, new Info(name, type, min, size, keepAlive, null)); } throw new ElasticsearchIllegalArgumentException("No type found [" + type + "], for [" + name + "]"); }
From source file:io.druid.cli.DumpSegment.java
private static <T> Sequence<T> executeQuery(final Injector injector, final QueryableIndex index, final Query<T> query) { final QueryRunnerFactoryConglomerate conglomerate = injector .getInstance(QueryRunnerFactoryConglomerate.class); final QueryRunnerFactory factory = conglomerate.findFactory(query); final QueryRunner<T> runner = factory.createRunner(new QueryableIndexSegment("segment", index)); final Sequence results = factory.getToolchest().mergeResults( factory.mergeRunners(MoreExecutors.sameThreadExecutor(), ImmutableList.<QueryRunner>of(runner))) .run(query, Maps.<String, Object>newHashMap()); return (Sequence<T>) results; }
From source file:com.google.sha1coin.kits.WalletAppKit.java
@Override protected void startUp() throws Exception { // Runs in a separate thread. if (!directory.exists()) { if (!directory.mkdir()) { throw new IOException("Could not create named directory."); }//from w w w. j a va 2 s .c om } log.info("Starting up with directory = {}", directory); try { File chainFile = new File(directory, filePrefix + ".spvchain"); boolean chainFileExists = chainFile.exists(); vWalletFile = new File(directory, filePrefix + ".wallet"); boolean shouldReplayWallet = (vWalletFile.exists() && !chainFileExists) || restoreFromSeed != null; vStore = new SPVBlockStore(params, chainFile); if ((!chainFileExists || restoreFromSeed != null) && checkpoints != null) { // Initialize the chain file with a checkpoint to speed up first-run sync. long time = Long.MAX_VALUE; if (restoreFromSeed != null) { time = restoreFromSeed.getCreationTimeSeconds(); if (chainFileExists) { log.info("Deleting the chain file in preparation from restore."); vStore.close(); if (!chainFile.delete()) throw new Exception("Failed to delete chain file in preparation for restore."); vStore = new SPVBlockStore(params, chainFile); } } else { // Ugly hack! We have to create the wallet once here to learn the earliest key time, and then throw it // away. The reason is that wallet extensions might need access to peergroups/chains/etc so we have to // create the wallet later, but we need to know the time early here before we create the BlockChain // object. if (vWalletFile.exists()) { FileInputStream stream = new FileInputStream(vWalletFile); final WalletProtobufSerializer serializer = new WalletProtobufSerializer(); final Wallet wallet = serializer.readWallet(params, null, WalletProtobufSerializer.parseToProto(stream)); time = wallet.getEarliestKeyCreationTime(); } } CheckpointManager.checkpoint(params, checkpoints, vStore, time); } vChain = new BlockChain(params, vStore); vPeerGroup = createPeerGroup(); if (this.userAgent != null) vPeerGroup.setUserAgent(userAgent, version); maybeMoveOldWalletOutOfTheWay(); if (vWalletFile.exists()) { FileInputStream walletStream = new FileInputStream(vWalletFile); try { List<WalletExtension> extensions = provideWalletExtensions(); vWallet = new Wallet(params); WalletExtension[] extArray = extensions.toArray(new WalletExtension[extensions.size()]); Protos.Wallet proto = WalletProtobufSerializer.parseToProto(walletStream); final WalletProtobufSerializer serializer; if (walletFactory != null) serializer = new WalletProtobufSerializer(walletFactory); else serializer = new WalletProtobufSerializer(); vWallet = serializer.readWallet(params, extArray, proto); if (shouldReplayWallet) vWallet.clearTransactions(0); } finally { walletStream.close(); } } else { vWallet = createWallet(); vWallet.freshReceiveKey(); for (WalletExtension e : provideWalletExtensions()) { vWallet.addExtension(e); } vWallet.saveToFile(vWalletFile); } if (useAutoSave) vWallet.autosaveToFile(vWalletFile, 200, TimeUnit.MILLISECONDS, null); // Set up peer addresses or discovery first, so if wallet extensions try to broadcast a transaction // before we're actually connected the broadcast waits for an appropriate number of connections. if (peerAddresses != null) { for (PeerAddress addr : peerAddresses) vPeerGroup.addAddress(addr); vPeerGroup.setMaxConnections(peerAddresses.length); peerAddresses = null; } else { vPeerGroup.addPeerDiscovery(new DnsDiscovery(params)); } vChain.addWallet(vWallet); vPeerGroup.addWallet(vWallet); onSetupCompleted(); if (blockingStartup) { vPeerGroup.startAsync(); vPeerGroup.awaitRunning(); // Make sure we shut down cleanly. installShutdownHook(); // TODO: Be able to use the provided download listener when doing a blocking startup. final DownloadListener listener = new DownloadListener(); vPeerGroup.startBlockChainDownload(listener); listener.await(); } else { vPeerGroup.startAsync(); vPeerGroup.addListener(new Service.Listener() { @Override public void running() { final PeerEventListener l = downloadListener == null ? new DownloadListener() : downloadListener; vPeerGroup.startBlockChainDownload(l); } @Override public void failed(State from, Throwable failure) { throw new RuntimeException(failure); } }, MoreExecutors.sameThreadExecutor()); } } catch (BlockStoreException e) { throw new IOException(e); } }
From source file:org.apache.cassandra.service.ActiveRepairService.java
/** * Submit anti-compaction jobs to CompactionManager. * When all jobs are done, parent repair session is removed whether those are suceeded or not. * * @param parentRepairSession parent repair session ID * @return Future result of all anti-compaction jobs. *///from w w w .ja v a2 s . co m @SuppressWarnings("resource") public ListenableFuture<List<Object>> doAntiCompaction(final UUID parentRepairSession, Collection<Range<Token>> successfulRanges) { assert parentRepairSession != null; ParentRepairSession prs = getParentRepairSession(parentRepairSession); //A repair will be marked as not global if it is a subrange repair to avoid many small anti-compactions //in addition to other scenarios such as repairs not involving all DCs or hosts if (!prs.isGlobal) { logger.info("Not a global repair, will not do anticompaction"); removeParentRepairSession(parentRepairSession); return Futures.immediateFuture(Collections.emptyList()); } assert prs.ranges.containsAll(successfulRanges) : "Trying to perform anticompaction on unknown ranges"; List<ListenableFuture<?>> futures = new ArrayList<>(); // if we don't have successful repair ranges, then just skip anticompaction if (!successfulRanges.isEmpty()) { for (Map.Entry<UUID, ColumnFamilyStore> columnFamilyStoreEntry : prs.columnFamilyStores.entrySet()) { Refs<SSTableReader> sstables = prs.getAndReferenceSSTables(columnFamilyStoreEntry.getKey()); ColumnFamilyStore cfs = columnFamilyStoreEntry.getValue(); futures.add(CompactionManager.instance.submitAntiCompaction(cfs, successfulRanges, sstables, prs.repairedAt)); } } ListenableFuture<List<Object>> allAntiCompactionResults = Futures.successfulAsList(futures); allAntiCompactionResults.addListener(new Runnable() { @Override public void run() { removeParentRepairSession(parentRepairSession); } }, MoreExecutors.sameThreadExecutor()); return allAntiCompactionResults; }
From source file:org.apache.druid.cli.DumpSegment.java
private static <T> Sequence<T> executeQuery(final Injector injector, final QueryableIndex index, final Query<T> query) { final QueryRunnerFactoryConglomerate conglomerate = injector .getInstance(QueryRunnerFactoryConglomerate.class); final QueryRunnerFactory<T, Query<T>> factory = conglomerate.findFactory(query); final QueryRunner<T> runner = factory.createRunner(new QueryableIndexSegment("segment", index)); return factory.getToolchest() .mergeResults(factory.mergeRunners(MoreExecutors.sameThreadExecutor(), ImmutableList.of(runner))) .run(QueryPlus.wrap(query), Maps.newHashMap()); }
From source file:org.opennms.features.vaadin.surveillanceviews.ui.dashboard.SurveillanceViewAlarmTable.java
/** * {@inheritDoc}//from w w w.j a v a 2 s . c om */ @Override public void refreshDetails(final Set<OnmsCategory> rowCategories, final Set<OnmsCategory> colCategories) { if (m_future != null && !m_future.isDone()) { return; } m_future = getSurveillanceViewService().getExecutorService().submit(new Callable<List<Alarm>>() { @Override public List<Alarm> call() throws Exception { /** * retrieve the matching alarms */ List<OnmsAlarm> onmsAlarms = getSurveillanceViewService().getAlarmsForCategories(rowCategories, colCategories); List<Alarm> alarms = new ArrayList<>(); Map<Integer, OnmsNode> nodeMap = new HashMap<>(); for (OnmsAlarm onmsAlarm : onmsAlarms) { if (!nodeMap.containsKey(onmsAlarm.getNodeId())) { nodeMap.put(onmsAlarm.getNodeId(), getSurveillanceViewService().getNodeForId(onmsAlarm.getNodeId())); } alarms.add(new Alarm(onmsAlarm.getId(), onmsAlarm.getUei(), onmsAlarm.getSeverityId(), onmsAlarm.getSeverity().getLabel(), nodeMap.get(onmsAlarm.getNodeId()).getLabel(), onmsAlarm.getNodeId(), onmsAlarm.getLogMsg(), onmsAlarm.getCounter(), onmsAlarm.getFirstEventTime(), onmsAlarm.getLastEventTime())); } return alarms; } }); m_future.addListener(new Runnable() { @Override public void run() { try { final List<Alarm> alarms = m_future.get(); getUI().access(new Runnable() { @Override public void run() { /** * empty the container */ m_beanItemContainer.removeAllItems(); /** * add items to container */ if (alarms != null && !alarms.isEmpty()) { for (Alarm alarm : alarms) { m_beanItemContainer.addItem(alarm); } } /** * sort the alarms */ sort(new Object[] { "severityId", "lastEventTime" }, new boolean[] { false, false }); /** * refresh the table */ refreshRowCache(); } }); } catch (InterruptedException e) { LOG.error("Interrupted", e); } catch (ExecutionException e) { LOG.error("Exception in task", e.getCause()); } } }, MoreExecutors.sameThreadExecutor()); }
From source file:org.opennms.features.vaadin.surveillanceviews.ui.dashboard.SurveillanceViewNotificationTable.java
/** * {@inheritDoc}/* w ww . j a v a 2 s. co m*/ */ @Override public void refreshDetails(final Set<OnmsCategory> rowCategories, final Set<OnmsCategory> colCategories) { if (m_future != null && !m_future.isDone()) { return; } m_future = getSurveillanceViewService().getExecutorService().submit(new Callable<List<Notification>>() { @Override public List<Notification> call() throws Exception { /** * create the custom severity map */ Map<OnmsNotification, String> customSeverity = new HashMap<>(); /** * retrieve the matching notifications */ List<OnmsNotification> onmsNotifications = getSurveillanceViewService() .getNotificationsForCategories(rowCategories, colCategories, customSeverity); /** * create the notifications list */ List<Notification> notifications = new ArrayList<>(); for (OnmsNotification onmsNotification : onmsNotifications) { notifications.add(new Notification(onmsNotification.getNotifyId(), onmsNotification.getNodeId(), onmsNotification.getNodeLabel(), onmsNotification.getPageTime(), onmsNotification.getRespondTime(), onmsNotification.getAnsweredBy(), onmsNotification.getTextMsg(), onmsNotification.getServiceType() != null ? onmsNotification.getServiceType().getName() : "", customSeverity.get(onmsNotification))); } return notifications; } }); m_future.addListener(new Runnable() { @Override public void run() { try { final List<Notification> notifications = m_future.get(); getUI().access(new Runnable() { @Override public void run() { /** * empty the bean container */ m_beanItemContainer.removeAllItems(); /** * add items to container */ if (notifications != null && !notifications.isEmpty()) { for (Notification notification : notifications) { m_beanItemContainer.addItem(notification); } } /** * sort the items */ sort(new Object[] { "pageTime" }, new boolean[] { false }); /** * refresh the table */ refreshRowCache(); } }); } catch (InterruptedException e) { LOG.error("Interrupted", e); } catch (ExecutionException e) { LOG.error("Exception in task", e.getCause()); } } }, MoreExecutors.sameThreadExecutor()); }
From source file:org.apache.hadoop.hive.ql.metadata.HiveMetaStoreChecker.java
/** * Assume that depth is 2, i.e., partition columns are a and b * tblPath/a=1 => throw exception//www .java 2 s. c om * tblPath/a=1/file => throw exception * tblPath/a=1/b=2/file => return a=1/b=2 * tblPath/a=1/b=2/c=3 => return a=1/b=2 * tblPath/a=1/b=2/c=3/file => return a=1/b=2 * * @param basePath * Start directory * @param allDirs * This set will contain the leaf paths at the end. * @param list * Specify how deep the search goes. * @throws IOException * Thrown if we can't get lists from the fs. * @throws HiveException */ private void checkPartitionDirs(Path basePath, Set<Path> allDirs, final List<String> partColNames) throws IOException, HiveException { // Here we just reuse the THREAD_COUNT configuration for // METASTORE_FS_HANDLER_THREADS_COUNT since this results in better performance // The number of missing partitions discovered are later added by metastore using a // threadpool of size METASTORE_FS_HANDLER_THREADS_COUNT. If we have different sized // pool here the smaller sized pool of the two becomes a bottleneck int poolSize = conf.getInt(ConfVars.METASTORE_FS_HANDLER_THREADS_COUNT.varname, 15); ExecutorService executor; if (poolSize <= 1) { LOG.debug("Using single-threaded version of MSCK-GetPaths"); executor = MoreExecutors.sameThreadExecutor(); } else { LOG.debug("Using multi-threaded version of MSCK-GetPaths with number of threads " + poolSize); ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("MSCK-GetPaths-%d").build(); executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(poolSize, threadFactory); } checkPartitionDirs(executor, basePath, allDirs, basePath.getFileSystem(conf), partColNames); executor.shutdown(); }