List of usage examples for java.util.concurrent ExecutorService execute
void execute(Runnable command);
From source file:org.springframework.integration.ftp.session.SessionFactoryTests.java
@Test @Ignore/*from w ww. java 2 s . c o m*/ public void testConnectionLimit() throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); DefaultFtpSessionFactory sessionFactory = new DefaultFtpSessionFactory(); sessionFactory.setHost("192.168.28.143"); sessionFactory.setPassword("password"); sessionFactory.setUsername("user"); final CachingSessionFactory factory = new CachingSessionFactory(sessionFactory, 2); final Random random = new Random(); final AtomicInteger failures = new AtomicInteger(); for (int i = 0; i < 30; i++) { executor.execute(new Runnable() { public void run() { try { Session session = factory.getSession(); Thread.sleep(random.nextInt(5000)); session.close(); } catch (Exception e) { e.printStackTrace(); failures.incrementAndGet(); } } }); } executor.shutdown(); executor.awaitTermination(10000, TimeUnit.SECONDS); assertEquals(0, failures.get()); }
From source file:br.prof.salesfilho.oci.view.console.Main.java
public void extractFeatures() { if (this.propertySource.containsProperty("inputDir") && this.propertySource.containsProperty("outputDir")) { //Create new thread pool to each image file ExecutorService executor = Executors.newFixedThreadPool(2); BodyWomanFeatureExtractorExecutor e1 = new BodyWomanFeatureExtractorExecutor(true); e1.setInputDir(this.propertySource.getProperty("inputDir").toString()); e1.setOutputDir(this.propertySource.getProperty("outputDir").toString()); e1.setKernelSize(Double.valueOf(this.propertySource.getProperty("kernelsize").toString())); e1.setDatabaseName(this.propertySource.getProperty("databaseName").toString()); executor.execute(e1); BodyWomanFeatureExtractorExecutor e2 = new BodyWomanFeatureExtractorExecutor(false); e2.setInputDir(this.propertySource.getProperty("inputDir").toString()); e2.setOutputDir(this.propertySource.getProperty("outputDir").toString()); e2.setKernelSize(Double.valueOf(this.propertySource.getProperty("kernelsize").toString())); e2.setDatabaseName(this.propertySource.getProperty("databaseName").toString()); executor.execute(e2);//from www.j a v a2 s .c o m //Wait finish executor.shutdown(); while (!executor.isTerminated()) { } File databaseFile = new File(e1.getDatabaseName()); bodyWomanDescriptorService.openDatabase(databaseFile); bodyWomanDescriptorService.add(e1.getBodyWomanDescriptor()); bodyWomanDescriptorService.add(e2.getBodyWomanDescriptor()); bodyWomanDescriptorService.save(databaseFile); } else { usage(); } }
From source file:org.wso2.appserver.integration.lazy.loading.artifacts.CarbonAppGhostDeploymentTestCase.java
@Test(groups = "wso2.as.lazy.loading", description = "Send concurrent requests when tenant context is not loaded." + "All request should get expected output", dependsOnMethods = "testTenantUnloadInIdleTimeAfterWebAPPInCarbonAppUsageInGhostDeployment", enabled = false) public void testConcurrentWebAPPInCarbonAppInvocationsWhenTenantContextNotLoadedInGhostDeployment() throws Exception { serverManager.restartGracefully();/* ww w . j a va 2s.co m*/ assertFalse(getTenantStatus(tenantDomain1).isTenantContextLoaded(), "Tenant context is loaded before access. Tenant name: " + tenantDomain1); ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_THREAD_COUNT); log.info("Concurrent invocation Start"); log.info("Expected Response Data:" + WEB_APP1_RESPONSE); for (int i = 0; i < CONCURRENT_THREAD_COUNT; i++) { executorService.execute(new Runnable() { public void run() { HttpResponse httpResponse = null; try { httpResponse = HttpURLConnectionClient.sendGetRequest(tenant1WebApp1URL, null); } catch (IOException ioException) { log.error("Error when sending a get request for :" + tenant1WebApp1URL, ioException); } synchronized (this) { String responseDetailedInfo; String responseData; if (httpResponse != null) { responseDetailedInfo = "Response Data :" + httpResponse.getData() + "\tResponse Code:" + httpResponse.getResponseCode(); responseData = httpResponse.getData(); } else { responseDetailedInfo = "Response Data : NULL Object return from HttpURLConnectionClient"; responseData = "NULL Object return "; } responseDataList.add(responseData); log.info(responseDetailedInfo); responseDetailedInfoList.add(responseDetailedInfo); } } }); } executorService.shutdown(); executorService.awaitTermination(5, TimeUnit.MINUTES); log.info("Concurrent invocation End"); int correctResponseCount = 0; for (String responseData : responseDataList) { if (WEB_APP1_RESPONSE.equals(responseData)) { correctResponseCount += 1; } } StringBuilder allDetailResponseStringBuffer = new StringBuilder(); allDetailResponseStringBuffer.append("\n"); for (String responseInfo : responseDetailedInfoList) { allDetailResponseStringBuffer.append(responseInfo); allDetailResponseStringBuffer.append("\n"); } String allDetailResponse = allDetailResponseStringBuffer.toString(); WebAppStatusBean webAppStatusTenant1WebApp1 = getWebAppStatus(tenantDomain1, CARBON_APP1_WEB_APP_FILE); assertTrue(webAppStatusTenant1WebApp1.getTenantStatus().isTenantContextLoaded(), " Tenant Context is" + " not loaded. Tenant:" + tenantDomain1); assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(), "Web-App: " + CARBON_APP1_WEB_APP_FILE + " is not started in Tenant:" + tenantDomain1); assertFalse(webAppStatusTenant1WebApp1.isWebAppGhost(), "Web-App: " + CARBON_APP1_WEB_APP_FILE + " is in ghost mode after invoking in Tenant:" + tenantDomain1); assertEquals(correctResponseCount, CONCURRENT_THREAD_COUNT, allDetailResponse + "All the concurrent requests " + "not get correct response."); }
From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java
/** * Scan all the class path and look for all classes that have the Format * Annotations./*from w w w .jav a2 s . c o m*/ */ public static void scanClassPathForFormattingAnnotations() { ExecutorService executorService = Executors .newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); // scan classpath and filter out classes that don't begin with "com.nds" Reflections reflections = new Reflections("com.nds", "com.cisco"); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class); // Reflections ciscoReflections = new Reflections("com.cisco"); // // annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class)); for (Class<?> markerClass : annotated) { // if the marker class is indeed implementing FoundationLoggingMarker // interface if (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) { final Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass; executorService.execute(new Runnable() { @Override public void run() { if (markersMap.get(clazz) == null) { try { // generate formatter class for this marker // class generateAndUpdateFormatterInMap(clazz); } catch (Exception e) { LOGGER.trace( "problem generating formatter class from static scan method. error is: " + e.toString()); } } } }); } else {// if marker class does not implement FoundationLoggingMarker // interface, log ERROR // verify the LOGGER was initialized. It might not be as this // Method is called in a static block if (LOGGER == null) { LOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class); } LOGGER.error("Formatter annotations should only appear on foundationLoggingMarker implementations"); } } executorService.shutdown(); // try { // executorService.awaitTermination(15, TimeUnit.SECONDS); // } catch (InterruptedException e) { // LOGGER.error("creation of formatters has been interrupted"); // } }
From source file:de.elomagic.mag.AbstractTest.java
protected Future<byte[]> createFileExistsFuture(Path file) { ExecutorService executor = Executors.newFixedThreadPool(2); FutureTask<byte[]> futureTask = new FutureTask<>(() -> { byte[] result = null; do {//from ww w . j a v a 2 s .c om if (Files.exists(file)) { InputStream in = Files.newInputStream(file, StandardOpenOption.READ); result = IOUtils.readFully(in, in.available()); } Thread.sleep(100); } while (result == null); return result; }); executor.execute(futureTask); return futureTask; }
From source file:org.orekit.utils.GenericTimeStampedCacheTest.java
private int checkDatesMultiThread(final List<AbsoluteDate> centralDates, final GenericTimeStampedCache<AbsoluteDate> cache, final int threadPoolSize) throws TimeStampedCacheException { final int n = cache.getNeighborsSize(); final double step = ((Generator) cache.getGenerator()).getStep(); final AtomicReference<AbsoluteDate[]> failedDates = new AtomicReference<AbsoluteDate[]>(); final AtomicReference<TimeStampedCacheException> caught = new AtomicReference<TimeStampedCacheException>(); ExecutorService executorService = Executors.newFixedThreadPool(threadPoolSize); for (final AbsoluteDate central : centralDates) { executorService.execute(new Runnable() { public void run() { try { final List<AbsoluteDate> neighbors = cache.getNeighbors(central); Assert.assertEquals(n, neighbors.size()); for (final AbsoluteDate date : neighbors) { if (date.durationFrom(central) < -(n + 1) * step || date.durationFrom(central) > n * step) { AbsoluteDate[] dates = new AbsoluteDate[n + 1]; dates[0] = central; System.arraycopy(neighbors, 0, dates, 1, n); failedDates.set(dates); }//from www . j a va 2s . c om } } catch (TimeStampedCacheException tce) { caught.set(tce); } } }); } try { executorService.shutdown(); Assert.assertTrue("Not enough time for all threads to complete, try increasing the timeout", executorService.awaitTermination(10, TimeUnit.MINUTES)); } catch (InterruptedException ie) { Assert.fail(ie.getLocalizedMessage()); } if (caught.get() != null) { throw caught.get(); } if (failedDates.get() != null) { AbsoluteDate[] dates = failedDates.get(); StringBuilder builder = new StringBuilder(); String eol = System.getProperty("line.separator"); builder.append("central = ").append(dates[0]).append(eol); builder.append("step = ").append(step).append(eol); builder.append("neighbors =").append(eol); for (int i = 1; i < dates.length; ++i) { builder.append(" ").append(dates[i]).append(eol); } Assert.fail(builder.toString()); } return centralDates.size(); }
From source file:org.wso2.appserver.integration.lazy.loading.artifacts.JaggeryApplicationGhostDeploymentTestCase.java
@Test(groups = "wso2.as.lazy.loading", description = "Send concurrent requests when tenant context is not loaded." + "All request should get expected output", dependsOnMethods = "testTenantUnloadInIdleTimeAfterJaggeryAPPUsageInGhostDeployment", enabled = false) public void testConcurrentJaggeryAPPInvocationsWhenTenantContextNotLoadedInGhostDeployment() throws Exception { serverManager.restartGracefully();/*from www .j av a 2 s . co m*/ assertFalse(getTenantStatus(tenantDomain1).isTenantContextLoaded(), "Tenant context is loaded before access. Tenant name: " + tenantDomain1); ExecutorService executorService = Executors.newFixedThreadPool(CONCURRENT_THREAD_COUNT); log.info("Concurrent invocation Start"); log.info("Expected Response Data:" + JAGG_APP1_RESPONSE); for (int i = 0; i < CONCURRENT_THREAD_COUNT; i++) { executorService.execute(new Runnable() { public void run() { HttpResponse httpResponse = null; try { httpResponse = HttpURLConnectionClient.sendGetRequest(tenant1JaggApp1Url, null); } catch (IOException e) { log.error("Error when sending a get request for :" + tenant1JaggApp1Url, e); } synchronized (this) { String responseDetailedInfo; String responseData; if (httpResponse != null) { responseDetailedInfo = "Response Data :" + httpResponse.getData() + "\tResponse Code:" + httpResponse.getResponseCode(); responseData = httpResponse.getData(); } else { responseDetailedInfo = "Response Data : NULL Object return from HttpURLConnectionClient"; responseData = "NULL Object return"; } responseDataList.add(responseData); log.info(responseDetailedInfo); responseDetailedInfoList.add(responseDetailedInfo); } } }); } executorService.shutdown(); executorService.awaitTermination(5, TimeUnit.MINUTES); log.info("Concurrent invocation End"); int correctResponseCount = 0; for (String responseData : responseDataList) { if (JAGG_APP1_RESPONSE.equals(responseData)) { correctResponseCount += 1; } } StringBuffer allDetailResponseStringBuffer = new StringBuffer(); allDetailResponseStringBuffer.append("\n"); for (String responseInfo : responseDetailedInfoList) { allDetailResponseStringBuffer.append(responseInfo); allDetailResponseStringBuffer.append("\n"); } String allDetailResponse = allDetailResponseStringBuffer.toString(); WebAppStatusBean webAppStatusTenant1WebApp1 = getWebAppStatus(tenantDomain1, JAGGERY_APP_NAME1); assertTrue(webAppStatusTenant1WebApp1.getTenantStatus().isTenantContextLoaded(), " Tenant Context is not loaded. Tenant:" + tenantDomain1); assertTrue(webAppStatusTenant1WebApp1.isWebAppStarted(), "Web-App: " + JAGGERY_APP_NAME1 + " is not started in Tenant:" + tenantDomain1); assertFalse(webAppStatusTenant1WebApp1.isWebAppGhost(), "Web-App: " + JAGGERY_APP_NAME1 + " is in ghost mode after invoking in Tenant:" + tenantDomain1); assertEquals(correctResponseCount, CONCURRENT_THREAD_COUNT, allDetailResponse + "All the concurrent requests " + "not get correct response."); }
From source file:org.commonjava.util.partyline.ClearCurrentThreadWithAnotherThreadReadingTest.java
/** * Given:/* w w w .j a v a 2 s.c o m*/ * <ul> * <li>Two threads, T1 and T2</li> * <li>One file containing some content, targeted for reading by both threads</li> * </ul> * <br/> * Sequence: * <br/> * <ol> * <li>T1 opens input stream</li> * <li>T1 reads from input stream</li> * <li>One of the following in unspecified order: * <ol type="A"> * <li>T1 waits for T2 to open input stream</li> * <li>T2 opens input stream</li> * </ol> * </li> * <li>T1 calls {@link JoinableFileManager#cleanupCurrentThread()}</li> * <li>T2 reads from input stream</li> * </ol> * <br/> * Expected Result: Both threads successfully read correct content from the file. */ @Test @BMUnitConfig(debug = true) public void run() throws Exception { final ExecutorService execs = Executors.newFixedThreadPool(2); CountDownLatch t1StartLatch = new CountDownLatch(1); CountDownLatch t2StartLatch = new CountDownLatch(1); CountDownLatch t1CleanupLatch = new CountDownLatch(1); final JoinableFileManager manager = new JoinableFileManager(); final String content = "This is a test"; final File file = temp.newFile(); FileUtils.write(file, content); List<String> returning = new ArrayList<String>(); execs.execute(() -> { Thread.currentThread().setName("T1"); readFile(null, t1StartLatch, null, manager, file, returning); try { logger.info("Waiting for T2 to get an input stream"); t2StartLatch.await(); } catch (InterruptedException e) { logger.warn(Thread.currentThread().getName() + " interrupted while waiting for second reader to open input stream."); } logger.info("Cleaning up T1 resources"); manager.cleanupCurrentThread(); logger.info("Signaling T1 cleanup is complete."); t1CleanupLatch.countDown(); }); execs.execute(() -> { Thread.currentThread().setName("T2"); readFile(t1StartLatch, t2StartLatch, t1CleanupLatch, manager, file, returning); }); completionLatch.await(); assertThat("Both threads should return content!", returning.size(), equalTo(2)); assertThat(returning.get(0), equalTo(content)); assertThat(returning.get(1), equalTo(content)); }
From source file:gridool.communication.transport.tcp.GridMasterSlaveWorkerServer.java
static boolean handleConnection(final Socket clientSocket, final GridTransportListener listener, final ExecutorService msgProcPool) { final InputStream is; final int size; try {/*from ww w . ja v a2 s. c om*/ is = clientSocket.getInputStream(); if (LOG.isDebugEnabled()) { final int available = is.available(); if (available == 0) { LOG.debug("Reading data from socket [" + clientSocket + "] seems to be blocked"); } } size = IOUtils.readUnsignedIntOrEOF(is); } catch (IOException e) { LOG.fatal(PrintUtils.prettyPrintStackTrace(e, -1)); return false; } if (size == -1) { if (LOG.isDebugEnabled()) { LOG.debug("Connection is closed by remote peer: " + clientSocket); } return false; } else if (size <= 0) { LOG.warn("Illegal message (size: " + size + ") was detected for a connection: " + clientSocket); return false; } if (LOG.isDebugEnabled()) { LOG.debug("Start reading " + size + " bytes from a socket [" + clientSocket + ']'); } // read an object from stream final byte[] b = new byte[size]; try { IOUtils.readFully(is, b, 0, size); } catch (IOException ioe) { LOG.fatal("Failed to read data from " + clientSocket, ioe); return false; } msgProcPool.execute(new Runnable() { public void run() { processRequest(b, listener, clientSocket); } }); return true; }
From source file:com.google.code.fqueue.memcached.TestFqueueServer.java
public void mutiThreadWrite() throws InterruptedException, TimeoutException, MemcachedException { int threadCount = 8; ExecutorService pool = Executors.newFixedThreadPool(threadCount); CountDownLatch latch = new CountDownLatch(threadCount); // MemcachedBenchJob.test = tester; MemcachedTest[] muti = new MemcachedTest[threadCount]; for (int i = 0; i < threadCount; i++) { muti[i] = new MemcachedTest(latch); }/* ww w .ja va2 s.c o m*/ log.info("start"); long start = System.currentTimeMillis(); for (int i = 0; i < threadCount; i++) { pool.execute(muti[i]); } latch.await(); long spend = System.currentTimeMillis() - start; log.info(threadCount + "threads:" + threadCount * 10000 + " spend:" + spend + " ms"); assertEquals(threadCount * 10000, getSize()); }