List of usage examples for java.util.concurrent ExecutorService submit
Future<?> submit(Runnable task);
From source file:org.green.code.async.executor.ThreadPoolTaskExecutor.java
public <T> Future<T> submit(Callable<T> task) { ExecutorService executor = getThreadPoolExecutor(); try {/*from w ww.j a va2 s .com*/ return executor.submit(task); } catch (RejectedExecutionException ex) { throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex); } }
From source file:be.vlaanderen.sesam.monitor.internal.util.ThreadPoolTaskScheduler.java
public Future<?> submit(Runnable task) { ExecutorService executor = getScheduledExecutor(); try {/*from w w w. j av a2s . c o m*/ return executor.submit(errorHandlingTask(task, false)); } catch (RejectedExecutionException ex) { throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex); } }
From source file:com.blacklocus.jres.request.index.JresUpdateDocumentTest.java
@Test public void testRetryOnConflict() throws InterruptedException { final String index = "JresUpdateDocumentTest.testRetryOnConflict".toLowerCase(); final String type = "test"; final String id = "warzone"; final AtomicReference<String> error = new AtomicReference<String>(); final int numThreads = 16, numIterations = 100; ExecutorService x = Executors.newFixedThreadPool(numThreads); for (int i = 0; i < numThreads; i++) { x.submit(new Runnable() { @Override/*from ww w. ja v a2 s.com*/ public void run() { try { for (int j = 0; j < numIterations; j++) { JresUpdateDocument req = new JresUpdateDocument(index, type, id, ImmutableMap.of("value", 0)); req.setRetryOnConflict(numIterations * 10); jres.quest(req); } } catch (Exception e) { error.set(e.getMessage()); } } }); } x.shutdown(); x.awaitTermination(1, TimeUnit.MINUTES); Assert.assertNull("With so many retries, all of these should have gotten through without conflict error", error.get()); jres.quest(new JresRefresh(index)); JresGetDocumentReply getReply = jres.quest(new JresGetDocument(index, type, id)); Map<String, Integer> doc = getReply.getSourceAsType(new TypeReference<Map<String, Integer>>() { }); Assert.assertEquals("Should have been numThreads * numIterations versions committed", (Object) (numThreads * numIterations), getReply.getVersion()); }
From source file:com.kurento.test.player.ParallelPlayerIT.java
private void testParallelPlay(String url, int statusCode, String contentType, boolean interrupt, String[] expectedHandlerFlow) throws ClientProtocolException, IOException, InterruptedException, ExecutionException { ExecutorService execute = Executors.newFixedThreadPool(nThreads); Collection<Future<?>> futures = new LinkedList<Future<?>>(); // Perform nThreads calls for (int i = 0; i < nThreads; i++) { futures.add(execute.submit( new PlayerTst(url, getServerPort(), statusCode, contentType, interrupt, expectedHandlerFlow))); }/*from ww w . jav a 2 s. co m*/ // Wait for all threads to be terminated for (Future<?> future : futures) { future.get(); } }
From source file:org.volkszaehler.android.JsonController.java
/** * A method that will execute a UrlConnect thread in the * given executionTime read from the globalStorage * @param urlConnect UrlConnect Instance that will be executed */// w w w .j av a 2s .co m private void executeUrlConnect(UrlConnect urlConnect) { converter = null; // Delete old data ExecutorService executor = Executors.newSingleThreadExecutor(); Future<?> future = executor.submit(urlConnect); try { // wait for task to complete int timer = globalStorage.getExecutionTime(); future.get(timer, TimeUnit.SECONDS); } catch (TimeoutException e) { errorMessage = "Timeout Exception"; } catch (InterruptedException e) { errorMessage = "Interrupted Exception"; } catch (ExecutionException e) { errorMessage = "Execution Exception"; } finally { executor.shutdownNow(); // cleanup } }
From source file:com.laxser.blitz.web.portal.impl.GenericWindowContainer.java
@SuppressWarnings({ "unchecked", "rawtypes" }) protected WindowFuture<?> submitWindow(ExecutorService executor, WindowTask task) { Future<?> future = executor.submit(task); return new WindowFuture(future, task.getWindow()); }
From source file:org.suren.autotest.web.framework.selenium.action.SeleniumFileUpload.java
@Override public boolean upload(Element element, final File file) { WebElement webEle = findElement(element); if (webEle != null) { logger.info("File upload, element is already found."); ExecutorService executor = Executors.newSingleThreadExecutor(); final AutoItCmd autoItCmd = new AutoItCmd(); try {/*from w ww . j av a 2 s . co m*/ Future<?> future = executor.submit(new Runnable() { @Override public void run() { try { autoItCmd.execFileChoose(file); } catch (Exception e) { e.printStackTrace(); } } }); synchronized (autoItCmd) { autoItCmd.wait(); } click(element); if (!future.isDone()) { future.get(30, TimeUnit.SECONDS); } return true; } catch (InterruptedException | ExecutionException | TimeoutException e) { logger.error("File uplod error.", e); e.printStackTrace(); } finally { autoItCmd.close(); executor.shutdown(); } } else { logger.error("Can not found element, when prepare to upload file."); } return false; }
From source file:com.opengamma.bbg.replay.BloombergTickWriterTest.java
@Test public void ticksWriting() throws Exception { ZonedDateTime startTime = ZonedDateTime.now(Clock.systemUTC()); //run test for 5secs long runTime = 5000; ExecutorService writerExecutor = Executors.newSingleThreadExecutor(); Future<?> writerFuture = writerExecutor.submit(_writer); //create ticks generators ExecutorService ticksGeneratorExec = Executors.newSingleThreadExecutor(); Future<?> ticksGenFuture = ticksGeneratorExec.submit(_ticksGenerator); s_logger.info("Test running for {}ms to generate ticks", runTime); Thread.sleep(runTime);//from w w w. j a va 2 s . c om //terminate ticks generation after 1mins _ticksGenerator.terminate(); sendTerminateMessage(); //test should fail if ticksGenerator throws an exception ticksGenFuture.get(); ticksGeneratorExec.shutdown(); ticksGeneratorExec.awaitTermination(1, TimeUnit.SECONDS); //test should fail if writer throws an exception writerFuture.get(); writerExecutor.shutdown(); writerExecutor.awaitTermination(1, TimeUnit.SECONDS); ZonedDateTime endTime = ZonedDateTime.now(Clock.systemUTC()); //now lets replay generated allTicks.dat Set<String> buids = Sets.newHashSet(_ticker2buid.values()); UnitTestTickReceiver receiver = new UnitTestTickReceiver(); BloombergTicksReplayer player = new BloombergTicksReplayer(Mode.AS_FAST_AS_POSSIBLE, _rootDir.getAbsolutePath(), receiver, startTime, endTime, buids); player.start(); while (player.isRunning()) { Thread.sleep(1000); } assertTrue(receiver.count() > 0); }
From source file:io.druid.segment.realtime.firehose.EventReceiverFirehoseTest.java
@Test public void testMultipleThreads() throws InterruptedException, IOException, TimeoutException, ExecutionException { EasyMock.expect(req.getContentType()).andReturn("application/json").times(2 * NUM_EVENTS); EasyMock.replay(req);// w ww. j av a2 s . co m final ExecutorService executorService = Execs.singleThreaded("single_thread"); final Future future = executorService.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { for (int i = 0; i < NUM_EVENTS; ++i) { final InputStream inputStream = IOUtils.toInputStream(inputRow); firehose.addAll(inputStream, req); inputStream.close(); } return true; } }); for (int i = 0; i < NUM_EVENTS; ++i) { final InputStream inputStream = IOUtils.toInputStream(inputRow); firehose.addAll(inputStream, req); inputStream.close(); } future.get(10, TimeUnit.SECONDS); EasyMock.verify(req); final Iterable<Map.Entry<String, EventReceiverFirehoseMetric>> metrics = register.getMetrics(); Assert.assertEquals(1, Iterables.size(metrics)); final Map.Entry<String, EventReceiverFirehoseMetric> entry = Iterables.getLast(metrics); Assert.assertEquals(SERVICE_NAME, entry.getKey()); Assert.assertEquals(CAPACITY, entry.getValue().getCapacity()); Assert.assertEquals(CAPACITY, firehose.getCapacity()); Assert.assertEquals(2 * NUM_EVENTS, entry.getValue().getCurrentBufferSize()); Assert.assertEquals(2 * NUM_EVENTS, firehose.getCurrentBufferSize()); for (int i = 2 * NUM_EVENTS - 1; i >= 0; --i) { Assert.assertTrue(firehose.hasMore()); Assert.assertNotNull(firehose.nextRow()); Assert.assertEquals(i, firehose.getCurrentBufferSize()); } Assert.assertEquals(CAPACITY, entry.getValue().getCapacity()); Assert.assertEquals(CAPACITY, firehose.getCapacity()); Assert.assertEquals(0, entry.getValue().getCurrentBufferSize()); Assert.assertEquals(0, firehose.getCurrentBufferSize()); firehose.close(); Assert.assertFalse(firehose.hasMore()); Assert.assertEquals(0, Iterables.size(register.getMetrics())); executorService.shutdownNow(); }
From source file:com.sonymobile.jenkins.plugins.lenientshutdown.PluginImpl.java
/** * Actually sets the node offline or prepares it to be leniently and then later offline. * * @param computer the computer.//from w ww .j a va 2s. c o m */ public void setNodeOffline(final Computer computer) { if (computer == null) { return; } final Node node = computer.getNode(); if (node == null) { return; } if (QueueUtils.isBuilding(computer) || QueueUtils.hasNodeExclusiveItemInQueue(computer)) { //Doing some work; we want to take offline leniently final String nodeName = node.getNodeName(); toggleNodeShuttingDown(nodeName); setOfflineByUser(nodeName, User.current()); ExecutorService service = new SecurityContextExecutorService(Executors.newSingleThreadExecutor()); service.submit(new Runnable() { @Override public void run() { Set<Long> permittedQueuedItemIds = getPermittedQueuedItemIds(nodeName); permittedQueuedItemIds.clear(); permittedQueuedItemIds.addAll(QueueUtils.getPermittedQueueItemIds(nodeName)); permittedQueuedItemIds.addAll(QueueUtils.getRunninProjectsQueueIDs(nodeName)); } }); } else { //No builds; we can take offline directly User currentUser = User.current(); if (currentUser == null) { currentUser = User.getUnknown(); } computer.setTemporarilyOffline(true, new LenientOfflineCause(currentUser)); } }