List of usage examples for java.util.concurrent ExecutorService execute
void execute(Runnable command);
From source file:alpine.event.framework.BaseEventService.java
/** * {@inheritDoc}/*from w w w. j av a 2 s . c o m*/ * @since 1.0.0 */ public void publish(Event event) { logger.debug("Dispatching event: " + event.getClass().toString()); final ArrayList<Class<? extends Subscriber>> subscriberClasses = subscriptionMap.get(event.getClass()); if (subscriberClasses == null) { logger.debug("No subscribers to inform from event: " + event.getClass().getName()); return; } for (Class<? extends Subscriber> clazz : subscriberClasses) { logger.debug("Alerting subscriber " + clazz.getName()); if (event instanceof ChainableEvent) { addTrackedEvent((ChainableEvent) event); } // Check to see if the Event is Unblocked. If so, use a separate executor pool from normal events final ExecutorService executorService = event instanceof UnblockedEvent ? dynamicExecutor : executor; executorService.execute(() -> { try (AlpineQueryManager qm = new AlpineQueryManager()) { final EventServiceLog eventServiceLog = qm.createEventServiceLog(clazz); final Subscriber subscriber = clazz.getDeclaredConstructor().newInstance(); subscriber.inform(event); qm.updateEventServiceLog(eventServiceLog); if (event instanceof ChainableEvent) { ChainableEvent chainableEvent = (ChainableEvent) event; logger.debug("Calling onSuccess"); for (ChainLink chainLink : chainableEvent.onSuccess()) { if (chainLink.getSuccessEventService() != null) { Method method = chainLink.getSuccessEventService().getMethod("getInstance"); IEventService es = (IEventService) method.invoke(chainLink.getSuccessEventService(), new Object[0]); es.publish(chainLink.getSuccessEvent()); } else { Event.dispatch(chainLink.getSuccessEvent()); } } } } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException | SecurityException e) { logger.error("An error occurred while informing subscriber: " + e); if (event instanceof ChainableEvent) { ChainableEvent chainableEvent = (ChainableEvent) event; logger.debug("Calling onFailure"); for (ChainLink chainLink : chainableEvent.onFailure()) { if (chainLink.getFailureEventService() != null) { try { Method method = chainLink.getFailureEventService().getMethod("getInstance"); IEventService es = (IEventService) method .invoke(chainLink.getFailureEventService(), new Object[0]); es.publish(chainLink.getFailureEvent()); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { logger.error("Exception while calling onFailure callback", ex); } } else { Event.dispatch(chainLink.getFailureEvent()); } } } } if (event instanceof ChainableEvent) { removeTrackedEvent((ChainableEvent) event); } }); } }
From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java
@Test(timeout = 5000) public void validateInfiniteJavaContainerLaunchForcedShutdown() throws Exception { final YarnApplication<Void> yarnApplication = YarnAssembly .forApplicationContainer(InfiniteContainer.class, ByteBuffer.wrap("Hello".getBytes())) .containerCount(4).memory(512).withApplicationMaster().maxAttempts(2).priority(2) .build("sample-yarn-application"); ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(new Runnable() { @Override//from w ww. ja v a 2 s .c o m public void run() { yarnApplication.launch(); } }); Thread.sleep(4000); assertTrue(yarnApplication.isRunning()); yarnApplication.terminate(); assertFalse(yarnApplication.isRunning()); executor.shutdown(); }
From source file:org.springframework.integration.aggregator.BarrierMessageHandlerTests.java
@Test public void testRequestBeforeReply() throws Exception { final BarrierMessageHandler handler = new BarrierMessageHandler(10000); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet();/*www. j a v a2 s. co m*/ final AtomicReference<Exception> dupCorrelation = new AtomicReference<Exception>(); final CountDownLatch latch = new CountDownLatch(1); Runnable runnable = () -> { try { handler.handleMessage(MessageBuilder.withPayload("foo").setCorrelationId("foo").build()); } catch (MessagingException e) { dupCorrelation.set(e); } latch.countDown(); }; ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(runnable); exec.execute(runnable); Map<?, ?> suspensions = TestUtils.getPropertyValue(handler, "suspensions", Map.class); int n = 0; while (n++ < 100 && suspensions.size() == 0) { Thread.sleep(100); } Map<?, ?> inProcess = TestUtils.getPropertyValue(handler, "inProcess", Map.class); assertEquals(1, inProcess.size()); assertTrue("suspension did not appear in time", n < 100); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNotNull(dupCorrelation.get()); assertThat(dupCorrelation.get().getMessage(), startsWith("Correlation key (foo) is already in use by")); handler.trigger(MessageBuilder.withPayload("bar").setCorrelationId("foo").build()); Message<?> received = outputChannel.receive(10000); assertNotNull(received); List<?> result = (List<?>) received.getPayload(); assertEquals("foo", result.get(0)); assertEquals("bar", result.get(1)); assertEquals(0, suspensions.size()); assertEquals(0, inProcess.size()); }
From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java
@Test(timeout = 2000) public void validateJavaContainerLaunchImmediateTermination() throws Exception { final YarnApplication<Void> yarnApplication = YarnAssembly .forApplicationContainer(SimpleRandomDelayContainer.class, ByteBuffer.wrap("Hello".getBytes())) .containerCount(2).memory(512).withApplicationMaster().maxAttempts(2).priority(2) .build("sample-yarn-application"); assertFalse(yarnApplication.isRunning()); ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(new Runnable() { @Override/* w ww.j a v a 2s . co m*/ public void run() { yarnApplication.launch(); } }); assertFalse(yarnApplication.isRunning()); yarnApplication.terminate(); assertEquals(0, yarnApplication.liveContainers()); assertFalse(yarnApplication.isRunning()); executor.shutdown(); }
From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java
@Test(timeout = 2000) public void validateContainerLaunchWithInfiniteCommandForcedShutdown() throws Exception { ClassPathResource resource = new ClassPathResource("infinite", this.getClass()); final YarnApplication<Void> yarnApplication = YarnAssembly .forApplicationContainer(resource.getFile().getAbsolutePath()).containerCount(3).memory(512) .withApplicationMaster().maxAttempts(2).priority(2).build("sample-yarn-application"); assertEquals(0, yarnApplication.liveContainers()); assertFalse(yarnApplication.isRunning()); ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(new Runnable() { @Override/*from www .j a v a 2 s .c o m*/ public void run() { yarnApplication.launch(); } }); while (yarnApplication.liveContainers() != 3) { LockSupport.parkNanos(1000); } assertTrue(yarnApplication.isRunning()); yarnApplication.terminate(); assertEquals(0, yarnApplication.liveContainers()); }
From source file:gridool.util.xfer.TransferServer.java
public void run() { final ExecutorService execPool = this.execPool; final TransferRequestListener handler = this.handler; try {/*from www . ja v a2s .c om*/ 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:com.linkedin.pinot.controller.helix.PinotResourceManagerTest.java
/** * Creates 5 threads that concurrently try to add 20 segments each, and asserts that we have * 100 segments in the end. Then launches 5 threads again that concurrently try to delete all segments, * and makes sure that we have zero segments left in the end. * @throws Exception/*w w w . j a v a 2 s.co m*/ */ @Test public void testConcurrentAddingAndDeletingSegments() throws Exception { ExecutorService addSegmentExecutor = Executors.newFixedThreadPool(5); for (int i = 0; i < 5; ++i) { addSegmentExecutor.execute(new Runnable() { @Override public void run() { for (int i = 0; i < 20; ++i) { addOneSegment(TABLE_NAME); try { Thread.sleep(1000); } catch (InterruptedException e) { Assert.assertFalse(true, "Exception caught during sleep."); } } } }); } addSegmentExecutor.shutdown(); while (!addSegmentExecutor.isTerminated()) { } final String offlineTableName = TableNameBuilder.OFFLINE_TABLE_NAME_BUILDER.forTable(TABLE_NAME); IdealState idealState = _helixAdmin.getResourceIdealState(HELIX_CLUSTER_NAME, offlineTableName); Assert.assertEquals(idealState.getPartitionSet().size(), 100); ExecutorService deleteSegmentExecutor = Executors.newFixedThreadPool(5); for (final String segment : idealState.getPartitionSet()) { deleteSegmentExecutor.execute(new Runnable() { @Override public void run() { deleteOneSegment(offlineTableName, segment); try { Thread.sleep(1000); } catch (InterruptedException e) { Assert.assertFalse(true, "Exception caught during sleep."); } } }); } deleteSegmentExecutor.shutdown(); while (!deleteSegmentExecutor.isTerminated()) { } idealState = _helixAdmin.getResourceIdealState(HELIX_CLUSTER_NAME, offlineTableName); Assert.assertEquals(idealState.getPartitionSet().size(), 0); }
From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java
@Test(timeout = 5000) @Ignore // fix to adgust for API changes public void validateJavaContainerLaunchAndVariableProcessTimeWithForcedShutdown() throws Exception { final YarnApplication<Void> yarnApplication = YarnAssembly .forApplicationContainer(VariableProcessingTime.class, ByteBuffer.wrap("Hello".getBytes())) .containerCount(6).memory(512).withApplicationMaster().maxAttempts(2).priority(2) .build("sample-yarn-application"); ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(new Runnable() { @Override/*w w w .ja v a 2 s .c o m*/ public void run() { yarnApplication.launch(); } }); // wait till all 6 are active while (yarnApplication.liveContainers() != 6) { LockSupport.parkNanos(10000); } System.out.println("Running: " + yarnApplication.isRunning()); // wait till some begin to shutdown while (yarnApplication.liveContainers() == 6) { LockSupport.parkNanos(10000); } System.out.println("Running: " + yarnApplication.isRunning()); assertTrue(yarnApplication.isRunning()); yarnApplication.terminate(); assertEquals(0, yarnApplication.liveContainers()); assertFalse(yarnApplication.isRunning()); }
From source file:org.hashes.CollisionInjector.java
/** * Run the specified clients on each thread. * // w w w . j a va 2 s. com * @param clients clients to run */ protected void runClients(final List<Runnable> clients) { Preconditions.checkNotNull(clients, "clients"); final int numberOfClients = clients.size(); if (LOG.isInfoEnabled()) { LOG.info("Starting " + clients.size() + " client(s)"); } final ExecutorService executor = Executors.newFixedThreadPool(numberOfClients); try { for (final Runnable client : clients) { executor.execute(client); } } finally { executor.shutdown(); } }
From source file:acromusashi.kafka.log.producer.LinuxApacheLogProducer.java
/** * ????Log?Tail?// w w w . j av a2s.c o m * * @param configMap ?Map */ protected void startTailLog(Map<String, Object> configMap) { String tailCommand = configMap.get("tail.command").toString(); String tailPath = configMap.get("tail.path").toString(); String tailCommandStr = tailCommand + " " + tailPath; String kafkaTopic = configMap.get("kafka.topic").toString(); String apacheLogFormat = configMap.get("apachelog.format").toString(); String jsonDateFormat = configMap.get("jsondate.format").toString(); String hostname = "defaultHost"; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ex) { logger.warn("HostName resolve failed. Use default. : default=" + hostname, ex); } ProducerConfig producerConfig = ProducerConfigConverter.convertToProducerConfig(configMap); logger.info("Producer starting. Command=" + tailCommandStr); ExecutorService executorService = Executors.newSingleThreadExecutor(); LinuxLogTailExecutor executor = new LinuxLogTailExecutor(tailCommandStr, kafkaTopic, apacheLogFormat, jsonDateFormat, hostname); executor.initialize(producerConfig); executorService.execute(executor); logger.info("Producer started"); }