List of usage examples for java.util.concurrent ExecutorService isShutdown
boolean isShutdown();
From source file:org.apache.bookkeeper.common.util.OrderedExecutor.java
/** * {@inheritDoc}//from w w w . j av a 2s.co m */ @Override public boolean isShutdown() { for (ExecutorService executor : threads) { if (!executor.isShutdown()) { return false; } } return true; }
From source file:com.ebay.jetstream.event.processor.esper.raw.EsperTest.java
@Ignore public void multithreadingTest() { Configuration configuration = new Configuration(); configuration.configure(// w w w.j a va 2 s . com new File("src/test/java/com/ebay/jetstream/event/processor/esper/raw/EsperTestConfig.xml")); EPServiceProvider epService = EPServiceProviderManager.getProvider("EsperTest", configuration); EsperTestStatement esperStmt = new EsperTestStatement(epService.getEPAdministrator()); EsperTestSubscriber subscriber = new EsperTestSubscriber(); EsperTestListener listener = new EsperTestListener(); esperStmt.setSubscriber(subscriber); esperStmt.addListener(listener); ExecutorService threadPool = Executors.newCachedThreadPool(new EsperTestThreadFactory()); EsperTestRunnable runnables[] = new EsperTestRunnable[THREADS_NUM]; try { for (int i = 0; i < THREADS_NUM; i++) { runnables[i] = new EsperTestRunnable(epService, i); threadPool.submit(runnables[i]); } threadPool.shutdown(); threadPool.awaitTermination(200, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("InterruptedException: " + e.getMessage()); } assertTrue("ExecutorService failed to shut down properly", threadPool.isShutdown()); log.info("[" + subscriber.getIds().first() + "," + subscriber.getIds().last() + "]"); assertEquals(THREADS_NUM, subscriber.getCount()); log.info("[" + listener.getIds().first() + "," + listener.getIds().last() + "]"); assertEquals(THREADS_NUM, listener.getCount()); assertEquals(THREADS_NUM, listener.getNewCount()); assertEquals(0, listener.getOldCount()); }
From source file:org.apache.hadoop.hbase.index.write.TestParalleIndexWriter.java
@Test public void testCorrectlyCleansUpResources() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(1); FakeTableFactory factory = new FakeTableFactory(Collections.<ImmutableBytesPtr, HTableInterface>emptyMap()); ParallelWriterIndexCommitter writer = new ParallelWriterIndexCommitter(); Abortable mockAbort = Mockito.mock(Abortable.class); Stoppable mockStop = Mockito.mock(Stoppable.class); // create a simple writer writer.setup(factory, exec, mockAbort, mockStop, 1); // stop the writer writer.stop(this.test.getTableNameString() + " finished"); assertTrue("Factory didn't get shutdown after writer#stop!", factory.shutdown); assertTrue("ExectorService isn't terminated after writer#stop!", exec.isShutdown()); Mockito.verifyZeroInteractions(mockAbort, mockStop); }
From source file:org.apache.phoenix.hbase.index.write.TestParalleIndexWriter.java
@Test public void testCorrectlyCleansUpResources() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(1); FakeTableFactory factory = new FakeTableFactory(Collections.<ImmutableBytesPtr, HTableInterface>emptyMap()); ParallelWriterIndexCommitter writer = new ParallelWriterIndexCommitter(VersionInfo.getVersion()); Abortable mockAbort = Mockito.mock(Abortable.class); Stoppable mockStop = Mockito.mock(Stoppable.class); // create a simple writer writer.setup(factory, exec, mockAbort, mockStop, 1); // stop the writer writer.stop(this.test.getTableNameString() + " finished"); assertTrue("Factory didn't get shutdown after writer#stop!", factory.shutdown); assertTrue("ExectorService isn't terminated after writer#stop!", exec.isShutdown()); Mockito.verifyZeroInteractions(mockAbort, mockStop); }
From source file:com.ebay.jetstream.event.processor.esper.raw.EsperTest.java
@Test public void aggregationTest() { Configuration configuration = new Configuration(); configuration.configure(/*from www . j ava 2 s . co m*/ new File("src/test/java/com/ebay/jetstream/event/processor/esper/raw/EsperTestConfig.xml")); EPServiceProvider epService = EPServiceProviderManager.getProvider("EsperTest", configuration); EsperTestAggregationStatement esperStmt = new EsperTestAggregationStatement(epService.getEPAdministrator()); EsperTestAggregationListener listener = new EsperTestAggregationListener(); esperStmt.addListener(listener); ExecutorService threadPool = Executors.newCachedThreadPool(new EsperTestThreadFactory()); EsperTestAggregationRunnable runnables[] = new EsperTestAggregationRunnable[THREADS_NUM_AGGRTEST]; try { for (int i = 0; i < THREADS_NUM_AGGRTEST; i++) { runnables[i] = new EsperTestAggregationRunnable(epService, i); threadPool.submit(runnables[i]); } threadPool.shutdown(); threadPool.awaitTermination(200, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("InterruptedException: " + e.getMessage()); } assertTrue("ExecutorService failed to shut down properly", threadPool.isShutdown()); assertEquals(THREADS_NUM_AGGRTEST * 2, listener.getCount()); assertEquals(THREADS_NUM_AGGRTEST, m_aggregationResults.size()); // only one result per oroginal event for (int i = 0; i < THREADS_NUM_AGGRTEST; i++) { assertEquals(11.0 + 4. * i, m_aggregationResults.get(i), 1.e-06); } assertEquals(THREADS_NUM_AGGRTEST, m_aggregationAvgResults.size()); // only one result per oroginal event for (int i = 0; i < THREADS_NUM_AGGRTEST; i++) { assertEquals((11.0 + 4. * i) / 4., m_aggregationAvgResults.get(i), 1.e-06); } }
From source file:com.ebay.jetstream.event.processor.esper.ESPTest.java
public void testProcessor() { EsperProcessor processor = getProcessor("ESPTestProcessor"); ESPTestSink sink = new ESPTestSink(); List<EventSink> sinks = new ArrayList<EventSink>(); sinks.add(sink);/* w ww .j av a 2 s.c o m*/ processor.setEventSinks(sinks); // TODO: start not exposed - processor.start(); // it was stopped while running previous test ExecutorService threadPool = Executors.newCachedThreadPool(new ESPTestThreadFactory()); Runnable runnables[] = new ESPTestRunnable[THREADS_NUM]; try { for (int i = 0; i < THREADS_NUM; i++) { runnables[i] = new ESPTestRunnable(processor, i); threadPool.submit(runnables[i]); } threadPool.shutdown(); threadPool.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { fail("InterruptedException: " + e.getMessage()); } assertTrue("ExecutorService failed to shut down properly", threadPool.isShutdown()); // processor.stop(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertEquals(THREADS_NUM, sink.getCount()); testLogger.info("sink first, last = [" + sink.getIds().first() + "," + sink.getIds().last() + "]"); }
From source file:com.nts.alphamale.handler.ExecutorHandler.java
/** * parallel execute synchronous commandline * @param cmdList/*from w w w . j a va2 s . com*/ * @param timeoutSecond * @return */ public List<Map<String, Object>> executeParallel(List<CommandLine> cmdList, int timeoutSecond) { ExecutorService executor = Executors.newCachedThreadPool(); List<Future<Map<String, Object>>> resultList; List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); List<SynchronousTask> taskList = new ArrayList<SynchronousTask>(); for (CommandLine cmd : cmdList) { taskList.add(new SynchronousTask(cmd, timeoutSecond * 1000)); } try { resultList = executor.invokeAll(taskList, timeoutSecond + 10, TimeUnit.SECONDS); for (Future<Map<String, Object>> result : resultList) { results.add(result.get()); } } catch (InterruptedException e) { log.error(e.getMessage()); } catch (ExecutionException e) { log.error(e.getMessage()); } if (!executor.isShutdown()) { executor.shutdown(); } return results; }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@Test public void testExecShutdown() { ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(new ImapMailReceiver()); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.initialize();/*from w w w . ja v a 2 s .c o m*/ adapter.setTaskScheduler(taskScheduler); adapter.start(); ExecutorService exec = TestUtils.getPropertyValue(adapter, "sendingTaskExecutor", ExecutorService.class); adapter.stop(); assertTrue(exec.isShutdown()); adapter.start(); exec = TestUtils.getPropertyValue(adapter, "sendingTaskExecutor", ExecutorService.class); adapter.stop(); assertTrue(exec.isShutdown()); }
From source file:org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.java
private Object invokeSEIMethod(Method method, Object[] args) throws Throwable { if (log.isDebugEnabled()) { log.debug("Attempting to invoke SEI Method " + method.getName()); }//from ww w. ja va 2 s .com OperationDescription operationDesc = endpointDesc.getEndpointInterfaceDescription().getOperation(method); // Create and configure the request MessageContext InvocationContext requestIC = InvocationContextFactory.createInvocationContext(null); MessageContext request = createRequest(method, args); request.getAxisMessageContext().setProperty(BINDING_PROVIDER, this); request.setEndpointDescription(getEndpointDescription()); request.setOperationDescription(operationDesc); // Enable MTOM on the Message if the property was set on the SOAPBinding. Binding bnd = (Binding) getBinding(); if (bnd != null && bnd instanceof SOAPBinding) { if (((SOAPBinding) bnd).isMTOMEnabled()) { Message requestMsg = request.getMessage(); requestMsg.setMTOMEnabled(true); int threshold = ((org.apache.axis2.jaxws.binding.SOAPBinding) bnd).getMTOMThreshold(); request.setProperty(org.apache.axis2.Constants.Configuration.MTOM_THRESHOLD, new Integer(threshold)); } if (((org.apache.axis2.jaxws.binding.SOAPBinding) bnd).isRespectBindingEnabled()) { //lets invoke Utility to configure RespectBinding. EndpointDescription endpointDescription = getEndpointDescription(); endpointDescription.setRespectBinding(true); WSDLExtensionUtils.processExtensions(endpointDescription); //We have build up set of extensions from wsdl //let go ahead and validate these extensions now. EndpointDescriptionValidator endpointValidator = new EndpointDescriptionValidator( endpointDescription); boolean isEndpointValid = endpointValidator.validate(true); //throw Exception if extensions are not understood by Engine. if (!isEndpointValid) { String msg = Messages.getMessage("endpointDescriptionValidationErrors", endpointValidator.toString()); throw ExceptionFactory.makeWebServiceException(msg); } } } /* * TODO: review: make sure the handlers are set on the InvocationContext * This implementation of the JAXWS runtime does not use Endpoint, which * would normally be the place to initialize and store the handler list. * In lieu of that, we will have to intialize and store them on the * InvocationContext. also see the InvocationContextFactory. On the client * side, the binding is not yet set when we call into that factory, so the * handler list doesn't get set on the InvocationContext object there. Thus * we gotta do it here. */ // be sure to use whatever handlerresolver is registered on the Service requestIC.setHandlers(bnd.getHandlerChain()); requestIC.setRequestMessageContext(request); requestIC.setServiceClient(serviceDelegate.getServiceClient(endpointDesc.getPortQName())); /* * if SESSION_MAINTAIN_PROPERTY is true, and the client app has explicitly set a HEADER_COOKIE on the request context, assume the client * app is expecting the HEADER_COOKIE to be the session id. If we were establishing a new session, no cookie would be sent, and the * server would reply with a "Set-Cookie" header, which is copied as a "Cookie"-keyed property to the service context during response. * In this case, if we succeed in using an existing server session, no "Set-Cookie" header will be returned, and therefore no * "Cookie"-keyed property would be set on the service context. So, let's copy our request context HEADER_COOKIE key to the service * context now to prevent the "no cookie" exception in BindingProvider.setupSessionContext. It is possible the server does not support * sessions, in which case no error occurs, but the client app would assume it is participating in a session. */ if ((requestContext.containsKey(BindingProvider.SESSION_MAINTAIN_PROPERTY)) && ((Boolean) requestContext.get(BindingProvider.SESSION_MAINTAIN_PROPERTY))) { if ((requestContext.containsKey(HTTPConstants.HEADER_COOKIE)) && (requestContext.get(HTTPConstants.HEADER_COOKIE) != null)) { if (requestIC.getServiceClient().getServiceContext() .getProperty(HTTPConstants.HEADER_COOKIE) == null) { requestIC.getServiceClient().getServiceContext().setProperty(HTTPConstants.HEADER_COOKIE, requestContext.get(HTTPConstants.HEADER_COOKIE)); if (log.isDebugEnabled()) { log.debug( "Client-app defined Cookie property (assume to be session cookie) on request context copied to service context." + " Caution: server may or may not support sessions, but client app will not be informed when not supported."); } } } } // Migrate the properties from the client request context bag to // the request MessageContext. ApplicationContextMigratorUtil.performMigrationToMessageContext( Constants.APPLICATION_CONTEXT_MIGRATOR_LIST_ID, getRequestContext(), request); // Note that configuring the MessageContext for addressing based on the metadata and for any // WebService Features needs to be done after the application context migration since it will move properties // from the JAXWS RequestContext onto the Axis2 Message context, overwritting any that are already set. configureAddressing(request, this); // Perform the WebServiceFeature configuration requested by the user. bnd.configure(request, this); // We'll need an InvocationController instance to send the request. InvocationControllerFactory icf = (InvocationControllerFactory) FactoryRegistry .getFactory(InvocationControllerFactory.class); controller = icf.getInvocationController(); if (controller == null) { throw new WebServiceException(Messages.getMessage("missingInvocationController")); } // Check if the call is OneWay, Async or Sync if (operationDesc.isOneWay()) { if (log.isDebugEnabled()) { log.debug("OneWay Call"); } controller.invokeOneWay(requestIC); // Check to see if we need to maintain session state checkMaintainSessionState(request, requestIC); } if (method.getReturnType() == Future.class) { if (log.isDebugEnabled()) { log.debug("Async Callback"); } //Get AsyncHandler from Objects and sent that to InvokeAsync AsyncHandler asyncHandler = null; for (Object obj : args) { if (obj != null && AsyncHandler.class.isAssignableFrom(obj.getClass())) { asyncHandler = (AsyncHandler) obj; break; } } // Don't allow the invocation to continue if the invocation requires a callback // object, but none was supplied. if (asyncHandler == null) { throw ExceptionFactory.makeWebServiceException(Messages.getMessage("proxyNullCallback")); } AsyncResponse listener = createProxyListener(args, operationDesc); requestIC.setAsyncResponseListener(listener); if ((serviceDelegate.getExecutor() != null) && (serviceDelegate.getExecutor() instanceof ExecutorService)) { ExecutorService es = (ExecutorService) serviceDelegate.getExecutor(); if (es.isShutdown()) { // the executor service is shutdown and won't accept new tasks // so return an error back to the client throw ExceptionFactory.makeWebServiceException(Messages.getMessage("ExecutorShutdown")); } } requestIC.setExecutor(serviceDelegate.getExecutor()); Future<?> future = controller.invokeAsync(requestIC, asyncHandler); //Check to see if we need to maintain session state checkMaintainSessionState(request, requestIC); if (log.isDebugEnabled()) { log.debug("Exiting the method invokeSEIMethod() - Async Callback "); } return future; } if (method.getReturnType() == Response.class) { if (log.isDebugEnabled()) { log.debug("Async Polling"); } AsyncResponse listener = createProxyListener(args, operationDesc); requestIC.setAsyncResponseListener(listener); requestIC.setExecutor(serviceDelegate.getExecutor()); Response response = controller.invokeAsync(requestIC); //Check to see if we need to maintain session state checkMaintainSessionState(request, requestIC); if (log.isDebugEnabled()) { log.debug("Exiting the method invokeSEIMethod() - Async Polling "); } return response; } if (!operationDesc.isOneWay()) { InvocationContext responseIC = controller.invoke(requestIC); //Check to see if we need to maintain session state checkMaintainSessionState(request, requestIC); MessageContext responseContext = responseIC.getResponseMessageContext(); // Migrate the properties from the response MessageContext back // to the client response context bag. ApplicationContextMigratorUtil.performMigrationFromMessageContext( Constants.APPLICATION_CONTEXT_MIGRATOR_LIST_ID, getResponseContext(), responseContext); Object responseObj = createResponse(method, args, responseContext, operationDesc); if (log.isDebugEnabled()) { log.debug("Exiting the method invokeSEIMethod() - Sync"); } return responseObj; } if (log.isDebugEnabled()) { log.debug("Exiting the method invokeSEIMethod() - One Way "); } return null; }
From source file:org.jactr.core.runtime.controller.OldController.java
/** * destory the executor service./*from w w w . j av a 2 s. c o m*/ * * @param service * @param model */ protected void destroyExecutorService(ExecutorService service, IModel model) { if (!service.isShutdown()) service.shutdown(); if (service instanceof ThreadPoolExecutor) { ThreadFactory factory = ((ThreadPoolExecutor) service).getThreadFactory(); if (factory instanceof GeneralThreadFactory) ((GeneralThreadFactory) factory).dispose(); } ExecutorServices.removeExecutor(model.getName()); }