List of usage examples for java.util.concurrent Executors newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads)
From source file:io.undertow.server.handlers.RequestLimitingHandlerTestCase.java
@Test public void testRateLimitingHandler() throws ExecutionException, InterruptedException { latch.countDown();/*from w w w.ja v a2 s .c om*/ latch = new CountDownLatch(1); ExecutorService executor = Executors.newFixedThreadPool(N_THREADS); try { final List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < N_THREADS; ++i) { futures.add(executor.submit(new Callable<String>() { @Override public String call() { TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL()); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); return HttpClientUtils.readResponse(result); } catch (IOException e) { throw new RuntimeException(e); } finally { client.getConnectionManager().shutdown(); } } })); } Thread.sleep(300); latch.countDown(); for (Future<?> future : futures) { String res = (String) future.get(); Assert.assertTrue(res, res.equals("1") || res.equals("2")); } } finally { executor.shutdown(); } }
From source file:es.upv.grycap.coreutils.fiber.test.FetchCancellationTest.java
@Test public void testFetch() throws Exception { // create fetcher final HttpDataFetcher fetcher = new HttpDataFetcher(2); assertThat("Fetcher was created", fetcher, notNullValue()); // create output folder final File outDir = tmpFolder.newFolder(randomAlphanumeric(12)); assertThat("Output dir was created", outDir, notNullValue()); assertThat("Output dir is writable", outDir.canWrite()); // submit request and cancel final ExecutorService executorService = Executors.newFixedThreadPool(2); final Future<Map<String, FetchStatus>> future = executorService .submit(new Callable<Map<String, FetchStatus>>() { @Override//w ww .j av a 2s . co m public Map<String, FetchStatus> call() throws Exception { return AsyncCompletionStage .get(fetcher.fetchToDir(new URL(MOCK_SERVER_BASE_URL + "/fetch/long-waiting"), ImmutableList.of("1"), outDir), 120000l, TimeUnit.SECONDS); } }); assertThat("Request was cancelled", future.cancel(true)); assertThat("File does not exist", not(new File(outDir, "1").exists())); }
From source file:com.marketplace.Main.java
/** * Creates <code>CategoryThread</code> for each Android Marketplace * Category./*from w w w . j ava 2 s .co m*/ * * @return a set containing <code>CategoryThread</code> */ private Set<Future<?>> createCategoryThread() { log.info("Creating threads for fetching apps via category."); Fetcher fetcher = new Fetcher(); ExecutorService executorService = Executors.newFixedThreadPool(22); Set<Future<?>> set = new HashSet<Future<?>>(); Session[] sessions = this.sessionManager.getSessions(); Iterator<String> categories = Category.getAllCategories(); for (int i = sessions.length; i > 0; i--) { while (categories.hasNext()) { set.add(executorService .submit(new CategoryThread(sessions[i - 1], fetcher, categories.next(), this.latest))); } categories = Category.getAllCategories(); } return set; }
From source file:com.expedia.seiso.Seiso.java
@Bean public ExecutorService executorService() { return Executors.newFixedThreadPool(8); }
From source file:edu.iu.daal_naive.NaiveUtil.java
static void generatePoints(int numOfDataPoints, int vectorSize, int numPointFiles, int nClasses, String localInputDir, FileSystem fs, Path dataDir) throws IOException, InterruptedException, ExecutionException { int pointsPerFile = numOfDataPoints / numPointFiles; System.out.println("Writing " + pointsPerFile + " vectors to a file"); // Check data directory if (fs.exists(dataDir)) { fs.delete(dataDir, true);// w w w . j av a 2 s .c o m } // Check local directory File localDir = new File(localInputDir); // If existed, regenerate data if (localDir.exists() && localDir.isDirectory()) { for (File file : localDir.listFiles()) { file.delete(); } localDir.delete(); } boolean success = localDir.mkdir(); if (success) { System.out.println("Directory: " + localInputDir + " created"); } if (pointsPerFile == 0) { throw new IOException("No point to write."); } // Create random data points int poolSize = Runtime.getRuntime().availableProcessors(); ExecutorService service = Executors.newFixedThreadPool(poolSize); List<Future<?>> futures = new LinkedList<Future<?>>(); for (int k = 0; k < numPointFiles; k++) { Future<?> f = service.submit( new DataGenNaiveBayes(localInputDir, Integer.toString(k), pointsPerFile, vectorSize, nClasses)); futures.add(f); // add a new thread } for (Future<?> f : futures) { f.get(); } // Shut down the executor service so that this // thread can exit service.shutdownNow(); // Wrap to path object Path localInput = new Path(localInputDir); fs.copyFromLocalFile(localInput, dataDir); }
From source file:com.devicehive.application.DeviceHiveApplication.java
@Lazy(false) @Bean(name = MESSAGE_EXECUTOR)/*from w w w. j a va 2 s. c o m*/ public ExecutorService messageExecutorService(@Value("${app.executor.size:1}") Integer executorSize) { return Executors.newFixedThreadPool(executorSize); }
From source file:com.espertech.esper.multithread.dispatchmodel.TestMTDispatch.java
private void trySend(int numThreads, int numCount, int ratioDoubleAdd, UpdateDispatchViewModel updateDispatchView, DispatchService dispatchService) throws Exception { // execute/*from w ww . ja v a 2 s . c o m*/ ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); Future future[] = new Future[numThreads]; DispatchCallable callables[] = new DispatchCallable[numThreads]; DispatchProducer producer = new DispatchProducer(updateDispatchView); for (int i = 0; i < numThreads; i++) { callables[i] = new DispatchCallable(producer, i, numCount, ratioDoubleAdd, updateDispatchView, dispatchService); future[i] = threadPool.submit(callables[i]); } threadPool.shutdown(); threadPool.awaitTermination(10, TimeUnit.SECONDS); for (int i = 0; i < numThreads; i++) { assertTrue((Boolean) future[i].get()); } }
From source file:fr.aliasource.webmail.proxy.impl.TimeOutMap.java
/** * @param timeout/* www . ja v a2 s. co m*/ * unused elements timeout in milliseconds */ public TimeOutMap(long timeout) { map = Collections.synchronizedMap(new HashMap<K, TimedItem<V>>()); this.timeout = timeout; executor = Executors.newFixedThreadPool(4); Timer t = new Timer(); t.scheduleAtFixedRate(new Remover(), 1000, timeout); }
From source file:com.espertech.esper.multithread.TestMTStmtNamedWindowSubqueryLookup.java
private void trySend(int numThreads, int numEventsPerThread) throws Exception { Configuration config = SupportConfigFactory.getConfiguration(); config.getEngineDefaults().getEventMeta() .setDefaultEventRepresentation(Configuration.EventRepresentation.MAP); // use Map-type events for testing config.addEventType("SupportBean", SupportBean.class); engine = EPServiceProviderManager.getDefaultProvider(config); engine.initialize();//from w w w . j a v a 2s . c om // setup statements engine.getEPAdministrator().createEPL("create schema MyUpdateEvent as (key string, intupd int)"); engine.getEPAdministrator().createEPL("create schema MySchema as (theString string, intval int)"); EPStatement namedWindow = engine.getEPAdministrator() .createEPL("create window MyWindow.win:keepall() as MySchema"); engine.getEPAdministrator() .createEPL("on MyUpdateEvent mue merge MyWindow mw " + "where mw.theString = mue.key " + "when not matched then insert select key as theString, intupd as intval " + "when matched then delete"); EPStatement targetStatement = engine.getEPAdministrator().createEPL( "select (select intval from MyWindow mw where mw.theString = sb.theString) as val from SupportBean sb"); // execute ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); Future<Boolean> future[] = new Future[numThreads]; for (int i = 0; i < numThreads; i++) { future[i] = threadPool.submit( new StmtNamedWindowSubqueryLookupCallable(i, engine, numEventsPerThread, targetStatement)); } threadPool.shutdown(); threadPool.awaitTermination(10, TimeUnit.SECONDS); // total up result for (int i = 0; i < numThreads; i++) { Boolean result = future[i].get(); assertTrue(result); } EventBean[] events = EPAssertionUtil.iteratorToArray(namedWindow.iterator()); assertEquals(0, events.length); }
From source file:biz.c24.io.spring.integration.samples.fpml.PreRenderingFpmlGenerator.java
private List<Generator> preRender() throws Exception { List<Generator> result = new ArrayList<Generator>(THREADS); final TradeConfirmed tradeConfirmed = readTradeConfirmed(); ExecutorCompletionService<Generator> completionService = new ExecutorCompletionService<Generator>( Executors.newFixedThreadPool(THREADS)); for (int i = 0; i < THREADS; i++) { completionService.submit(new Callable<Generator>() { public Generator call() throws Exception { System.out.println("Rendering... "); OutputType ot = OutputType.BYTE_ARRAY; Random rand = new Random(); TradeConfirmed myTradeConfirmed = (TradeConfirmed) tradeConfirmed.cloneDeep(); Generator gen = new Generator(); List<Object> payloads = new ArrayList<Object>(ITERATIONS); for (int j = 0; j < ITERATIONS; j++) { TradeConfirmed fpML = randomizeFpML(myTradeConfirmed); if (rand.nextInt(100) == 0) { breakFpml(fpML); }// w ww . java2 s. co m Sink sink = ot.getSink(sinkFactory); sink.writeObject(fpML); Object payload = ot.getOutput(sink); payloads.add(payload); } gen.payloads = payloads; return gen; } }); } for (int i = 0; i < THREADS; i++) { Future<Generator> future = completionService.take(); result.add(future.get()); } return result; }