List of usage examples for java.util.concurrent ExecutorService execute
void execute(Runnable command);
From source file:com.sastix.cms.server.services.cache.UIDServiceTest.java
@Test public void massiveUIDCreatorTest() throws InterruptedException { String region1 = "r1"; String region2 = "r2"; regionIdsMap.put(region1, new HashMap<>()); regionIdsMap.put(region2, new HashMap<>()); ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); for (int i = 0; i < numberOfTasks; i++) { String region = region1;/*w w w .j a v a 2s. c o m*/ if (i % 2 == 0) { region = region2; } Runnable worker = new UIDRunnable(region); executor.execute(worker); } try { latch.await(); } catch (InterruptedException E) { // handle } executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); assertEquals(numberOfTasks, ids.size()); assertEquals(numberOfTasks / 2, regionIdsMap.get(region1).size()); assertEquals(numberOfTasks / 2, regionIdsMap.get(region2).size()); assertTrue(!duplicateFound); LOG.info("Finished all threads"); }
From source file:com.adaptris.core.lifecycle.FilteredSharedComponentStart.java
private void execute(final ConnectionAction action, final AdaptrisConnection comp) throws CoreException { if (threadedStart()) { ExecutorService myExecutor = getExecutor(comp.getUniqueId()); final String threadName = this.getClass().getSimpleName(); myExecutor.execute(new Runnable() { @Override//from ww w .j a v a 2s.c o m public void run() { Thread.currentThread().setName(threadName); try { action.invoke(comp); } catch (Exception e) { log.error("Failed to {} connection {}", action, friendlyName(comp), e); } } }); } else { action.invoke(comp); } }
From source file:gridool.communication.transport.tcp.GridNioServer.java
private static void handleRead(final SocketChannel channel, final SelectionKey key, final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) { sharedReadBuf.clear();/*from w ww . j av a2 s . co m*/ final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress(); final int bytesRead; try { bytesRead = channel.read(sharedReadBuf); } catch (IOException e) { LOG.warn("Failed to read data from client: " + remoteAddr, e); NIOUtils.close(key); return; } if (LOG.isDebugEnabled()) { LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr); } if (bytesRead == -1) { if (LOG.isTraceEnabled()) { LOG.trace("Remote client closed connection: " + remoteAddr); } NIOUtils.close(key); return; } else if (bytesRead == 0) { return; } final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment(); sharedReadBuf.flip(); while (sharedReadBuf.remaining() > 0) { msgBuf.read(sharedReadBuf); if (msgBuf.isFilled()) { exec.execute(new Runnable() { public void run() { final GridCommunicationMessage msg = msgBuf.toMessage(); msgBuf.reset(); if (LOG.isDebugEnabled()) { LOG.debug("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]"); } notifier.notifyListener(msg); } }); break; } } }
From source file:it.unibo.alchemist.modelchecker.AlchemistASMC.java
/** * @param xmlFilePath//from www .ja v a2 s . c om * Alchemist XML specification to execute * @param steps * maximum length of the simulation in steps * @param finalTime * maximum length of the simulation in simulated time units */ public void execute(final String xmlFilePath, final long steps, final double finalTime) { final ExecutorService ex = Executors.newSingleThreadExecutor(); ex.execute(new Runnable() { public void run() { try { nr = minN; final byte[] ba = mx.serializedEnvironment(xmlFilePath); EnvironmentBuilder<T> ebo; ebo = new EnvironmentBuilder<>(xmlFilePath); ebo.buildEnvironment(); final RandomEngine random = new MersenneTwister(); random.setSeed(ebo.getRandomEngine().getSeed()); mx.addJob(ba, random, minN, steps, finalTime); mx.waitForCompletion(); notifyASMCListeners(); while (!stopCondition()) { nr += SAMPLESTEP; // pList.ensureCapacity(INCREASE); mx.addJob(ba, random, SAMPLESTEP, steps, finalTime); mx.waitForCompletion(); notifyASMCListeners(); } mx.destroy(); exec.release(); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | SAXException | IOException | ParserConfigurationException e) { L.error(e); } } }); }
From source file:org.biopax.validator.impl.ValidatorImpl.java
private void execute(ExecutorService exec, final Set<Rule<?>> rules, final Validation validation, final Object obj) { exec.execute(new Runnable() { @SuppressWarnings("unchecked") //obj can be either Model or a BPE public void run() { for (Rule rule : rules) { Behavior behavior = utils.getRuleBehavior(rule.getClass().getName(), validation.getProfile()); if (behavior == Behavior.IGNORE) continue; // skip disabled rule try { if (rule.canCheck(obj)) rule.check(validation, obj); } catch (Throwable t) { //if we're here, there is probably a bug in the rule or validator! String id = validation.identify(obj); log.fatal(rule + ".check(" + id + ") threw the exception: " + t.toString(), t); // anyway, report it almost normally (for a user to see this in the results too) validation.addError( utils.createError(id, "exception", rule.getClass().getName(), null, false, t)); }/*from w w w . j av a 2s .com*/ } } }); }
From source file:org.yamj.core.service.ScanningScheduler.java
@Scheduled(initialDelay = 5000, fixedDelay = 45000) public void scanMediaFiles() throws Exception { int maxThreads = configService.getIntProperty("yamj3.scheduler.mediafilescan.maxThreads", 1); if (maxThreads <= 0 || !mediaInfoService.isMediaInfoActivated()) { if (!messageDisabledMediaFiles) { messageDisabledMediaFiles = Boolean.TRUE; LOG.info("Media file scanning is disabled"); }//from w w w . j a v a 2 s. c om return; } else { messageDisabledMediaFiles = Boolean.FALSE; } int maxResults = configService.getIntProperty("yamj3.scheduler.mediafilescan.maxResults", 20); List<QueueDTO> queueElements = mediaStorageService.getMediaFileQueueForScanning(maxResults); if (CollectionUtils.isEmpty(queueElements)) { LOG.debug("No media files found to scan"); return; } LOG.info("Found {} media files to process; scan with {} threads", queueElements.size(), maxThreads); BlockingQueue<QueueDTO> queue = new LinkedBlockingQueue<QueueDTO>(queueElements); ExecutorService executor = Executors.newFixedThreadPool(maxThreads); for (int i = 0; i < maxThreads; i++) { MediaInfoRunner worker = new MediaInfoRunner(queue, mediaInfoService); executor.execute(worker); } executor.shutdown(); // run until all workers have finished while (!executor.isTerminated()) { try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException ignore) { } } LOG.debug("Finished media file scanning"); }
From source file:org.mule.modules.jmsbatchmessaging.JmsBatchMessagingConnector.java
/** * Consume messages in batches from a JMS destination. * <p/>/*from w w w .ja v a 2s. c o m*/ * {@sample.xml ../../../doc/jms-batch-messaging-connector.xml.sample * jms-batch-messaging:consume} * * @param destinationName The JMS destination to consume messages from * @param amountOfThreads The amount of threads used to consume messages in parallel batches * @param batchSize The size of each batch * @param timeout The timeout, in milliseconds, to wait before releasing a batch that hasn't received its full batch of messages * @param isTopic Whether or not the JMS destination is a topic. * @throws Exception */ @Source public void consume(String destinationName, int amountOfThreads, Boolean isTopic, int batchSize, long timeout, final SourceCallback callback) throws Exception { Lock lock = null; try { lock = muleContext.getLockFactory().createLock("JMS_BATCH_MESSAGING_CONSUMER_LOCK"); lock.lock(); logger.debug(String.format("Starting batch (size=%s) processing with %s threads", batchSize, amountOfThreads)); ExecutorService executorService = Executors.newFixedThreadPool(amountOfThreads); for (int i = 0; i < amountOfThreads; i++) { executorService.execute(new DestinationMessageConsumer(muleContext, batchSize, timeout, callback, connector, destinationName, isTopic, isTransactional)); } executorService.shutdown(); try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { logger.debug("Thread interrupted"); } } finally { if (lock != null) { lock.unlock(); } } }
From source file:org.apache.hadoop.fs.swift.TestSwiftFileSystemConcurrency.java
/** * test on concurrent file system changes *//*w w w . j a va 2 s.c o m*/ @Test(timeout = SWIFT_TEST_TIMEOUT) public void testRaceConditionOnDirDeleteTest() throws Exception { SwiftTestUtils.skip("Skipping unreliable test"); final String message = "message"; final Path fileToRead = new Path(TEST_RACE_CONDITION_ON_DELETE_DIR + "/files/many-files/file"); final ExecutorService executorService = Executors.newFixedThreadPool(2); fs.create(new Path(TEST_RACE_CONDITION_ON_DELETE_DIR + "/file/test/file1")); fs.create(new Path(TEST_RACE_CONDITION_ON_DELETE_DIR + "/documents/doc1")); fs.create(new Path(TEST_RACE_CONDITION_ON_DELETE_DIR + "/pictures/picture")); executorService.execute(new Runnable() { @Override public void run() { try { assertDeleted(new Path(TEST_RACE_CONDITION_ON_DELETE_DIR), true); } catch (IOException e) { LOG.warn("deletion thread:" + e, e); thread1Ex = e; throw new RuntimeException(e); } } }); executorService.execute(new Runnable() { @Override public void run() { try { final FSDataOutputStream outputStream = fs.create(fileToRead); outputStream.write(message.getBytes()); outputStream.close(); } catch (IOException e) { LOG.warn("writer thread:" + e, e); thread2Ex = e; throw new RuntimeException(e); } } }); executorService.awaitTermination(1, TimeUnit.MINUTES); if (thread1Ex != null) { throw thread1Ex; } if (thread2Ex != null) { throw thread2Ex; } try { fs.open(fileToRead); LOG.info("concurrency test failed to trigger a failure"); } catch (FileNotFoundException expected) { } }
From source file:com.sastix.cms.common.services.htmltopdf.PdfTest.java
@Test public void performanceTest() throws InterruptedException { int NTHREDS = 30;//the lesser the threads, the completion time increases. At least 15 threads for better performance on my laptop ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); long start = DateTime.now().getMillis(); for (int i = 0; i < numberOfTasks; i++) { Runnable worker = new PdfRunnable(i, "<html><head><meta charset=\"utf-8\"></head><h1>Mller</h1></html>"); executor.execute(worker); }//from w w w. j a v a2s. com try { latch.await(); } catch (InterruptedException E) { // handle } executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); assertEquals(cmap.size(), numberOfTasks); long passed = DateTime.now().getMillis() - start; LOG.info("Millis passed: " + passed); LOG.info("Seconds passed: " + (double) passed / 1000); }
From source file:org.kie.workbench.common.services.datamodel.backend.server.ModuleDataModelConcurrencyTest.java
@Test public void testConcurrentResourceUpdates() throws URISyntaxException { final URL pomUrl = this.getClass().getResource("/DataModelBackendTest1/pom.xml"); final org.uberfire.java.nio.file.Path nioPomPath = ioService.get(pomUrl.toURI()); final Path pomPath = paths.convert(nioPomPath); final URL resourceUrl = this.getClass().getResource("/DataModelBackendTest1/src/main/resources/empty.rdrl"); final org.uberfire.java.nio.file.Path nioResourcePath = ioService.get(resourceUrl.toURI()); final Path resourcePath = paths.convert(nioResourcePath); //Force full build before attempting incremental changes final KieModule module = moduleService.resolveModule(resourcePath); final BuildResults buildResults = buildService.build(module); assertNotNull(buildResults);/*w ww. j a v a 2s . c o m*/ assertEquals(0, buildResults.getErrorMessages().size()); assertEquals(1, buildResults.getInformationMessages().size()); //Perform incremental build final int THREADS = 200; final Result result = new Result(); ExecutorService es = Executors.newCachedThreadPool(); for (int i = 0; i < THREADS; i++) { final int operation = (i % 3); switch (operation) { case 0: es.execute(new Runnable() { @Override public void run() { try { logger.debug("[Thread: " + Thread.currentThread().getName() + "] Request to update POM received"); invalidateCaches(module, pomPath); buildChangeListener.updateResource(pomPath); logger.debug("[Thread: " + Thread.currentThread().getName() + "] POM update completed"); } catch (Throwable e) { result.setFailed(true); result.setMessage(e.getMessage()); ExceptionUtils.printRootCauseStackTrace(e); } } }); break; case 1: es.execute(new Runnable() { @Override public void run() { try { logger.debug("[Thread: " + Thread.currentThread().getName() + "] Request to update Resource received"); invalidateCaches(module, resourcePath); buildChangeListener.addResource(resourcePath); logger.debug( "[Thread: " + Thread.currentThread().getName() + "] Resource update completed"); } catch (Throwable e) { result.setFailed(true); result.setMessage(e.getMessage()); ExceptionUtils.printRootCauseStackTrace(e); } } }); break; case 2: es.execute(new Runnable() { @Override public void run() { try { logger.debug("[Thread: " + Thread.currentThread().getName() + "] Request for DataModel received"); dataModelService.getDataModel(resourcePath); logger.debug("[Thread: " + Thread.currentThread().getName() + "] DataModel request completed"); } catch (Throwable e) { result.setFailed(true); result.setMessage(e.getMessage()); ExceptionUtils.printRootCauseStackTrace(e); } } }); } } es.shutdown(); try { es.awaitTermination(5, TimeUnit.MINUTES); } catch (InterruptedException e) { } if (result.isFailed()) { fail(result.getMessage()); } }