List of usage examples for java.util.concurrent ExecutorService submit
Future<?> submit(Runnable task);
From source file:com.espertech.esper.multithread.TestMTStmtSharedView.java
private void trySend(int numThreads, int numRepeats, int numStatements) throws Exception { // Create same statement X times EPStatement stmt[] = new EPStatement[numStatements]; SupportMTUpdateListener listeners[] = new SupportMTUpdateListener[stmt.length]; for (int i = 0; i < stmt.length; i++) { stmt[i] = engine.getEPAdministrator().createEPL(" select * " + " from " + SupportMarketDataBean.class.getName() + ".std:groupwin(symbol).stat:uni(price)"); listeners[i] = new SupportMTUpdateListener(); stmt[i].addListener(listeners[i]); }/*from w ww. jav a 2 s. co m*/ // Start send threads // Each threads sends each symbol with price = 0 to numRepeats long startTime = System.currentTimeMillis(); ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); Future future[] = new Future[numThreads]; for (int i = 0; i < numThreads; i++) { Callable callable = new StmtSharedViewCallable(numRepeats, engine, SYMBOLS); future[i] = threadPool.submit(callable); } // Shut down threadPool.shutdown(); threadPool.awaitTermination(10, TimeUnit.SECONDS); for (int i = 0; i < numThreads; i++) { assertTrue((Boolean) future[i].get()); } long endTime = System.currentTimeMillis(); long delta = endTime - startTime; assertTrue("delta=" + delta + " not less then 5 sec", delta < 5000); // should take less then 5 seconds even for 100 statements as they need to share resources thread-safely // Assert results for (SupportMTUpdateListener listener : listeners) { assertEquals(numRepeats * numThreads * SYMBOLS.length, listener.getNewDataList().size()); EventBean[] newDataLast = listener.getNewDataList().get(listener.getNewDataList().size() - 1); assertEquals(1, newDataLast.length); EventBean result = newDataLast[0]; assertEquals(numRepeats * numThreads, ((Long) result.get("datapoints")).longValue()); assertTrue(Arrays.asList(SYMBOLS).contains(result.get("symbol"))); assertEquals(sumToN(numRepeats) * numThreads, result.get("total")); listener.reset(); } for (int i = 0; i < stmt.length; i++) { stmt[i].stop(); } }
From source file:cherry.chart.app.LineChartBatch.java
@Override public ExitStatus execute(String... args) { int nThread = (args.length < 1 ? defaultNumThread : parseInt(args[0])); int count = (args.length < 2 ? defaultCount : parseInt(args[1])); ExecutorService executorService = Executors.newFixedThreadPool(nThread); List<Future<Boolean>> tasks = new LinkedList<>(); for (int i = 0; i < count; i++) { final String numStr = String.valueOf(i); tasks.add(executorService.submit(new Callable<Boolean>() { @Override//from www. ja v a 2 s .c o m public Boolean call() { File f = new File(toDir, format(file, numStr)); String t = format(title, numStr); CategoryDataset dataset = createDataset(); JFreeChart chart = ChartFactory.createLineChart(t, xLabel, yLabel, dataset); try (OutputStream out = new FileOutputStream(f)) { ChartUtilities.writeChartAsPNG(out, chart, width, height); return true; } catch (IOException ex) { log.error("failed to create file", ex); return false; } } })); } boolean success = true; for (Future<Boolean> future : tasks) { try { success &= future.get(); } catch (ExecutionException | InterruptedException ex) { log.error("failed to get result", ex); success = false; } } return (success ? ExitStatus.NORMAL : ExitStatus.ERROR); }
From source file:com.test.HibernateDerbyLockingTest.java
public void runTest(final SessionFactory sessionFactory) throws Exception { Person person = new Person(); Session session = sessionFactory.openSession(); session.save(person);/*from w ww. j a v a2 s . c om*/ session.flush(); session.close(); final String id = person.getId(); final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(); ExecutorService executorService = Executors.newCachedThreadPool(); Future<?> submit = executorService.submit(new Runnable() { public void run() { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.load(Person.class, id, LockMode.UPGRADE); try { Thread.sleep(2000); } catch (Throwable t) { } System.out.println("one"); queue.add("one"); try { Thread.sleep(500); } catch (Throwable t) { } transaction.commit(); session.flush(); session.close(); } }); Thread.sleep(500); Future<?> submit2 = executorService.submit(new Runnable() { public void run() { Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.load(Person.class, id, LockMode.UPGRADE); queue.add("two"); System.out.println("two"); transaction.commit(); session.flush(); session.close(); } }); submit.get(); submit2.get(); assertEquals("one", queue.poll(3, TimeUnit.SECONDS)); assertEquals("two", queue.poll(3, TimeUnit.SECONDS)); }
From source file:com.sonymobile.jenkins.plugins.lenientshutdown.ShutdownManageLink.java
/** * Toggles the flag and prepares for lenient shutdown if needed. * *///w ww . j a v a 2 s . co m public void performToggleGoingToShutdown() { toggleGoingToShutdown(); if (isGoingToShutdown()) { ExecutorService service = new SecurityContextExecutorService(Executors.newSingleThreadExecutor()); service.submit(new Runnable() { @Override public void run() { permittedQueueIds.clear(); activeQueueIds.clear(); whiteListedQueueIds.clear(); permittedQueueIds.addAll(QueueUtils.getPermittedQueueItemIds()); permittedQueueIds.addAll(QueueUtils.getRunningProjectQueueIds()); activeQueueIds.addAll(permittedQueueIds); analyzing = false; } }); } }
From source file:io.undertow.server.handlers.RequestLimitingHandlerTestCase.java
@Test public void testRateLimitingHandler() throws ExecutionException, InterruptedException { latch.countDown();// ww w. j a v a2s . co m 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:com.hortonworks.hbase.BufferedMutatorExample.java
@Override public int run(String[] args) throws InterruptedException, ExecutionException, TimeoutException { /** a callback invoked when an asynchronous write fails. */ final BufferedMutator.ExceptionListener listener = new BufferedMutator.ExceptionListener() { @Override/*www .j a v a2 s.c o m*/ public void onException(RetriesExhaustedWithDetailsException e, BufferedMutator mutator) { for (int i = 0; i < e.getNumExceptions(); i++) { LOG.info("Failed to send put " + e.getRow(i) + "."); } } }; BufferedMutatorParams params = new BufferedMutatorParams(TABLE).listener(listener); // // step 1: create a single Connection and a BufferedMutator, shared by all worker threads. // Configuration conf = new Configuration(); try (final Connection conn = ConnectionFactory.createConnection(conf); final BufferedMutator mutator = conn.getBufferedMutator(params)) { conf.set("hbase.zookeeper.quorum", "sandbox.hortonworks.com"); conf.set("hbase.zookeeper.property.clientPort", "2181"); conf.set("zookeeper.znode.parent", "/hbase-unsecure"); // conf.set("hbase.zookeeper.quorum", "jetmaster2.jetnetname.artem.com,jetslave5.jetnetname.artem.com,jetslave1.jetnetname.artem.com"); // conf.set("hbase.zookeeper.property.clientPort", "2181"); // conf.set("zookeeper.znode.parent", "/hbase-unsecure"); /** worker pool that operates on BufferedTable instances */ final ExecutorService workerPool = Executors.newFixedThreadPool(POOL_SIZE); List<Future<Void>> futures = new ArrayList<>(TASK_COUNT); for (int i = 0; i < TASK_COUNT; i++) { futures.add(workerPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { // // step 2: each worker sends edits to the shared BufferedMutator instance. They all use // the same backing buffer, call-back "listener", and RPC executor pool. // Put p = new Put(Bytes.toBytes("someRow")); p.addColumn(FAMILY, Bytes.toBytes("someQualifier"), Bytes.toBytes("some value")); mutator.mutate(p); // do work... maybe you want to call mutator.flush() after many edits to ensure any of // this worker's edits are sent before exiting the Callable return null; } })); } // // step 3: clean up the worker pool, shut down. // for (Future<Void> f : futures) { f.get(5, TimeUnit.MINUTES); } workerPool.shutdown(); } catch (IOException e) { // exception while creating/destroying Connection or BufferedMutator LOG.info("exception while creating/destroying Connection or BufferedMutator", e); } // BufferedMutator.close() ensures all work is flushed. Could be the custom listener is // invoked from here. return 0; }
From source file:com.serphacker.serposcope.task.proxy.ProxyChecker.java
@Override public void run() { LOG.info("starting proxy checking task, threads = {}, timeout in MS = {}", nThread, timeoutMS); long start = System.currentTimeMillis(); List<Proxy> proxies = db.proxy.list(); if (proxies == null || proxies.isEmpty()) { LOG.debug("no proxy to check"); return;/* www . ja v a 2 s. com*/ } totalProxies = proxies.size(); ExecutorService executor = Executors.newFixedThreadPool(nThread); db.proxy.updateStatus(Proxy.Status.UNCHECKED, proxies.stream().map((t) -> t.getId()).collect(Collectors.toList())); for (Proxy proxy : proxies) { executor.submit(new Runnable() { @Override public void run() { ScrapClient cli = new ScrapClient(); cli.setTimeout(timeoutMS); ScrapProxy scrapProxy = proxy.toScrapProxy(); cli.setProxy(scrapProxy); LOG.info("checking {}", scrapProxy); Proxy.Status proxyStatus = Proxy.Status.ERROR; // try{Thread.sleep(30000l);}catch(Exception ex){} int httpStatus = cli.get(judgeUrl); if (httpStatus == 200 && cli.getContentAsString() != null) { Matcher matcher = PATTERN_IP.matcher(cli.getContentAsString()); if (matcher.find()) { proxy.setRemoteip(matcher.group(1)); proxyStatus = Proxy.Status.OK; } } proxy.setStatus(proxyStatus); proxy.setLastCheck(LocalDateTime.now()); db.proxy.update(proxy); checked.incrementAndGet(); } }); } executor.shutdown(); try { executor.awaitTermination(1, TimeUnit.HOURS); } catch (InterruptedException ex) { executor.shutdownNow(); } LOG.info("proxy checking finished in {}", DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start)); }
From source file:org.bpmscript.process.hibernate.SpringHibernateInstanceManagerTest.java
public void testInstanceManagerLocking() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "/org/bpmscript/endtoend/spring.xml"); try {/*from w ww. j ava 2s. com*/ final IInstanceManager instanceManager = (IInstanceManager) context.getBean("instanceManager"); final String pid1 = instanceManager.createInstance("parentVersion", "definitionId", "test", IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "one"); IInstance instance = instanceManager.getInstance(pid1); assertNotNull(instance); instanceManager.createInstance("parentVersion", "definitionId", "test", IJavascriptProcessDefinition.DEFINITION_TYPE_JAVASCRIPT, "two"); ExecutorService executorService = Executors.newFixedThreadPool(2); final AtomicReference<Queue<String>> results = new AtomicReference<Queue<String>>( new LinkedList<String>()); executorService.submit(new Callable<Object>() { public Object call() throws Exception { return instanceManager.doWithInstance(pid1, new IInstanceCallback() { public IExecutorResult execute(IInstance instance) throws Exception { log.info("locking one"); Thread.sleep(2000); results.get().add("one"); return new IgnoredResult("", "", ""); } }); } }); Thread.sleep(100); Future<Object> future2 = executorService.submit(new Callable<Object>() { public Object call() throws Exception { return instanceManager.doWithInstance(pid1, new IInstanceCallback() { public IExecutorResult execute(IInstance instance) throws Exception { log.info("locking two"); results.get().add("two"); return new IgnoredResult("", "", ""); } }); } }); future2.get(); assertEquals(2, results.get().size()); assertEquals("one", results.get().poll()); assertEquals("two", results.get().poll()); } finally { context.destroy(); } }
From source file:com.bigdata.dastor.db.Memtable.java
public void flushAndSignal(final Condition condition, ExecutorService sorter, final ExecutorService writer) { cfs.getMemtablesPendingFlush().add(this); // it's ok for the MT to briefly be both active and pendingFlush writer.submit(new WrappedRunnable() { public void runMayThrow() throws IOException { cfs.addSSTable(writeSortedContents()); cfs.getMemtablesPendingFlush().remove(Memtable.this); condition.signalAll();// w w w .ja v a 2 s .c o m } }); }
From source file:at.alladin.rmbt.util.tools.InformationCollectorTool.java
public void start(final ExecutorService executor) { final long startTimeNs = System.nanoTime(); if (!this.running.get()) { running.set(true);/*ww w . j a v a 2s . c om*/ executor.submit(new Runnable() { public void run() { try { while (InformationCollectorTool.this.running.get()) { update(); Thread.sleep(PAUSE_BETWEEN_AUTO_EXECUTION_IN_MS); final long executingTimeNs = System.nanoTime() - startTimeNs; if (executingTimeNs >= TimeUnit.NANOSECONDS.convert(timeout.get(), deltaTimeUnit)) { System.out.println("Timeout reached. Stopping InformationCollectorTool"); InformationCollectorTool.this.running.set(false); } } } catch (InterruptedException e) { e.printStackTrace(); } running.set(false); } }); } }