List of usage examples for java.util.concurrent ExecutorService shutdown
void shutdown();
From source file:com.microsoft.azure.servicebus.samples.queuesgettingstarted.QueuesGettingStarted.java
public void run(String connectionString) throws Exception { // Create a QueueClient instance for receiving using the connection string builder // We set the receive mode to "PeekLock", meaning the message is delivered // under a lock and must be acknowledged ("completed") to be removed from the queue QueueClient receiveClient = new QueueClient(new ConnectionStringBuilder(connectionString, "BasicQueue"), ReceiveMode.PEEKLOCK);//from w ww .j a v a2 s. c o m // We are using single thread executor as we are only processing one message at a time ExecutorService executorService = Executors.newSingleThreadExecutor(); this.registerReceiver(receiveClient, executorService); // Create a QueueClient instance for sending and then asynchronously send messages. // Close the sender once the send operation is complete. QueueClient sendClient = new QueueClient(new ConnectionStringBuilder(connectionString, "BasicQueue"), ReceiveMode.PEEKLOCK); this.sendMessagesAsync(sendClient).thenRunAsync(() -> sendClient.closeAsync()); // wait for ENTER or 10 seconds elapsing waitForEnter(10); // shut down receiver to close the receive loop receiveClient.close(); executorService.shutdown(); }
From source file:werecloud.api.bean.VMWareMacCache.java
private void initializeMACCache() throws RemoteException, InterruptedException { long start = System.currentTimeMillis(); ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine"); ExecutorService exec = Executors.newFixedThreadPool(loadThreads); try {//from w ww. j a v a2 s. c om for (final ManagedEntity me : mes) { exec.submit(new Runnable() { @Override public void run() { VirtualMachine vm = (VirtualMachine) me; addVirtualMachine(vm); } }); } } finally { exec.shutdown(); } exec.awaitTermination(1, TimeUnit.HOURS); logger.info("{} MAC addresses added and took {} milliseconds.", macAddresses.size(), System.currentTimeMillis() - start); }
From source file:com.microsoft.aad.adal4jsample.BasicFilter.java
private AuthenticationResult getAccessTokenFromRefreshToken(String refreshToken) throws Throwable { AuthenticationContext context;//from w w w . ja va 2s.co m AuthenticationResult result = null; ExecutorService service = null; try { service = Executors.newFixedThreadPool(1); context = new AuthenticationContext(authority + tenant + "/", true, service); Future<AuthenticationResult> future = context.acquireTokenByRefreshToken(refreshToken, new ClientCredential(clientId, clientSecret), null, null); result = future.get(); } catch (ExecutionException e) { throw e.getCause(); } finally { service.shutdown(); } if (result == null) { throw new ServiceUnavailableException("authentication result was null"); } return result; }
From source file:gridool.util.xfer.TransferServer.java
public void run() { final ExecutorService execPool = this.execPool; final TransferRequestListener handler = this.handler; try {/* w w w. j a va 2 s. co m*/ while (true) { SocketChannel channel = serverChannel.accept(); execPool.execute(new RequestHandler(channel, handler)); } } catch (ClosedByInterruptException interrupted) { if (LOG.isDebugEnabled()) { LOG.debug("Avoidable interrupt happened (Normal case): " + interrupted.getMessage()); } } catch (IOException ioe) { LOG.error(ioe); } catch (Throwable th) { LOG.error(th); } finally { execPool.shutdown(); try { serverChannel.close(); } catch (IOException ie) { if (LOG.isDebugEnabled()) { LOG.debug(PrintUtils.prettyPrintStackTrace(ie, -1)); } } } }
From source file:biz.fstechnology.micro.server.jms.AbstractJmsService.java
/** * @see javax.jms.MessageListener#onMessage(javax.jms.Message) *///ww w . j a v a 2 s . c o m @Override public void onMessage(Message message) { try { ExecutorService executor = Executors.newSingleThreadExecutor(); if (((ObjectMessage) message).getObject() instanceof Result) { // no op return; } Request<?> request = (Request<?>) ((ObjectMessage) message).getObject(); // cast hell... Future<Request<?>> preProcessFuture = executor.submit(() -> onPreProcessRequest(request)); Future<Result<?>> resultFuture = executor.submit(() -> processRequest(preProcessFuture.get())); Future<Result<?>> postProcessFuture = executor .submit(() -> onPostProcessRequest(request, resultFuture.get())); executor.shutdown(); Result<?> result = postProcessFuture.get(); ResponseMessageCreator messageCreator = new ResponseMessageCreator(); messageCreator.setContents(result); messageCreator.setRequestId(message.getJMSCorrelationID()); replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session)); } catch (JMSException | InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); Result<Object> result = new Result<>(e); try { ResponseMessageCreator messageCreator = new ResponseMessageCreator(); messageCreator.setContents(result); messageCreator.setRequestId(message.getJMSCorrelationID()); replyProducer.send(message.getJMSReplyTo(), messageCreator.createMessage(session)); } catch (JmsException | JMSException e1) { e1.printStackTrace(); } } }
From source file:com.netflix.curator.framework.recipes.leader.TestLeaderLatch.java
private void basic(Mode mode) throws Exception { final int PARTICIPANT_QTY = 1;//0; List<LeaderLatch> latches = Lists.newArrayList(); Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try {//from w w w . j a v a 2 s . c om client.start(); for (int i = 0; i < PARTICIPANT_QTY; ++i) { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); if (mode == Mode.START_IMMEDIATELY) { latch.start(); } latches.add(latch); } if (mode == Mode.START_IN_THREADS) { ExecutorService service = Executors.newFixedThreadPool(latches.size()); for (final LeaderLatch latch : latches) { service.submit(new Callable<Object>() { @Override public Object call() throws Exception { Thread.sleep((int) (100 * Math.random())); latch.start(); return null; } }); } service.shutdown(); } while (latches.size() > 0) { List<LeaderLatch> leaders = waitForALeader(latches, timing); Assert.assertEquals(leaders.size(), 1); // there can only be one leader LeaderLatch theLeader = leaders.get(0); if (mode == Mode.START_IMMEDIATELY) { Assert.assertEquals(latches.indexOf(theLeader), 0); // assert ordering - leadership should advance in start order } theLeader.close(); latches.remove(theLeader); } } finally { for (LeaderLatch latch : latches) { IOUtils.closeQuietly(latch); } IOUtils.closeQuietly(client); } }
From source file:com.laudandjolynn.mytv.crawler.CrawlerGroup.java
@Override public List<TvStation> crawlAllTvStation() { List<TvStation> resultList = new ArrayList<TvStation>(); int size = crawlers.size(); int maxThreadNum = Constant.CPU_PROCESSOR_NUM; ThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("Mytv_CrawlerGroup_%d") .build();/*w w w.jav a2 s . co m*/ ExecutorService executorService = Executors.newFixedThreadPool(size > maxThreadNum ? maxThreadNum : size, threadFactory); CompletionService<List<TvStation>> completionService = new ExecutorCompletionService<List<TvStation>>( executorService); for (final Crawler crawler : crawlers) { Callable<List<TvStation>> task = new Callable<List<TvStation>>() { @Override public List<TvStation> call() throws Exception { return crawler.crawlAllTvStation(); } }; completionService.submit(task); } executorService.shutdown(); int count = 0; while (count < size) { try { List<TvStation> stationList = completionService.take().get(); if (stationList != null) { resultList.addAll(stationList); } } catch (InterruptedException e) { logger.error("crawl task of all tv station interrupted.", e); } catch (ExecutionException e) { logger.error("crawl task of all tv station executed fail.", e); } count++; } for (CrawlEventListener listener : listeners) { listener.crawlEnd(new AllTvStationCrawlEndEvent(this, resultList)); } return resultList; }
From source file:models.Search.java
/** * @param request The clients request/*w w w .j a v a2 s . co m*/ * @param serialization The wanted serialization of the returned data. * @return the chunks of the elasticsearch scroll scan query */ public Chunks<String> executeScrollScan(final Request request, final Serialization serialization) { validateSearchParameters(); return new StringChunks() { @Override public void onReady(Chunks.Out<String> out) { setMessageOut(out); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { doingScrollScanNow = true; bulk(request, serialization); } }); executorService.shutdown(); } }; }
From source file:com.mobilecashout.osprey.remote.RemoteClient.java
private synchronized void executeInParallel(RemoteRunnable runnable, DeploymentContext context, String[] roles) {//from w w w. ja v a 2s. c om if (null == roles) { roles = new String[] { "all" }; } while (!semaphore.tryAcquire()) { try { Thread.sleep(100); } catch (InterruptedException e) { context.setFailed(); throw new RuntimeException(e); } } final ExecutorService pool = Executors.newFixedThreadPool(sessions.size()); final ArrayList<Future<Boolean>> futures = new ArrayList<>(); for (RemoteTarget remoteTarget : sessions) { if (!remoteTarget.getTarget().hasAnyRole(roles)) { continue; } Future<Boolean> executor = pool.submit(() -> { runnable.run(remoteTarget, context); return true; }); futures.add(executor); } pool.shutdown(); try { pool.awaitTermination(Integer.MAX_VALUE, TimeUnit.MINUTES); for (Future future : futures) { future.get(); } Thread.sleep(100); } catch (InterruptedException | ExecutionException e) { context.setFailed(); logger.fatal(e.getMessage(), e); } finally { semaphore.release(); } }
From source file:com.pliu.powerbiintegrate.BasicFilter.java
private AuthenticationResult getAccessToken(AuthorizationCode authorizationCode, String currentUri) throws Throwable { String authCode = authorizationCode.getValue(); ClientCredential credential = new ClientCredential(clientId, clientSecret); AuthenticationContext context;/*from w ww . j a v a 2s .c o m*/ AuthenticationResult result = null; ExecutorService service = null; try { service = Executors.newFixedThreadPool(1); context = new AuthenticationContext(authority + tenant + "/", true, service); Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, "https://analysis.windows.net/powerbi/api", null); result = future.get(); } catch (ExecutionException e) { throw e.getCause(); } finally { service.shutdown(); } if (result == null) { throw new ServiceUnavailableException("authentication result was null"); } return result; }