Example usage for java.util.concurrent ExecutorService execute

List of usage examples for java.util.concurrent ExecutorService execute

Introduction

In this page you can find the example usage for java.util.concurrent ExecutorService execute.

Prototype

void execute(Runnable command);

Source Link

Document

Executes the given command at some time in the future.

Usage

From source file:com.aerospike.benchmarks.Main.java

private void doAsyncInserts(AsyncClient client) throws Exception {
    ExecutorService es = Executors.newFixedThreadPool(this.nThreads);

    // Create N insert tasks
    int ntasks = this.nThreads < this.nKeys ? this.nThreads : this.nKeys;
    int start = this.startKey;
    int keysPerTask = this.nKeys / ntasks + 1;

    for (int i = 0; i < ntasks; i++) {
        InsertTask it = new InsertTaskAsync(client, args, counters, start, keysPerTask);
        es.execute(it);
        start += keysPerTask;/*from w  w  w  .  j  a va  2  s  .  c  o m*/
    }
    collectInsertStats();
    es.shutdownNow();
}

From source file:com.sec.ose.osi.thread.ui_related.UserRequestHandler.java

public UIResponseObserver handle(int pRequestCode, UIEntity pEntity, boolean pDisplayProgress,
        boolean pShowSuccessResult) {

    final int NUMBER_THREADS = 2;
    ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_THREADS);

    UIResponseObserver observer = new DefaultUIResponseObserver();
    UserCommandExecutionThread xExecutionThread = new UserCommandExecutionThread(pRequestCode, pEntity,
            observer);/* w  w  w.  j  a va 2s .c om*/

    // Option 1:
    //      in case: pDisplayProgress == true
    //       need to display progress dialog

    if (pDisplayProgress == true) {

        // 1-1. create Progress Dialog

        ProgressDisplayer progressDisplayer = ProgressDisplayerFactory
                .getProgressDisplayer(UISharedData.getInstance().getCurrentFrame(), pRequestCode);

        // 1-2. Execute Monitor Thread
        UserCommandExecutionMonitorThread xMonitorThread = new UserCommandExecutionMonitorThread(
                progressDisplayer, observer);
        xExecutionThread.setMonitorThread(xMonitorThread);

        // 1-3. execute

        executorService.execute(xMonitorThread);
        executorService.execute(xExecutionThread);

        progressDisplayer.setVisible(true); // block here

        // 1-5. close remained thread

        if (progressDisplayer.isCancled() == true && xExecutionThread.isDone() == false) {
            log.debug("canceled");
            xExecutionThread.cancel();

            log.debug("isDone: " + xExecutionThread.isDone());
            xExecutionThread = null;
            observer.setFailMessage("canceled");

            executorService.shutdown();
            return observer;
        }
    }

    // Option 2:
    //      in case: pDisplayProgress == false
    //       no need to display progress dialog

    else {
        // 2-1. execute
        executorService.execute(xExecutionThread);

        // 2-2. waiting for completing execution
        while (xExecutionThread.isDone() == false) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                log.warn(e);
            }
        }
    }

    // Mandatory STEP
    //       display result

    int result = observer.getResult();

    // opt1. the execution result is "SUCCESS"
    if (result == UIResponseObserver.RESULT_SUCCESS) {

        if (pShowSuccessResult == true) {
            JOptionPane.showMessageDialog(UISharedData.getInstance().getCurrentFrame(),
                    observer.getSuccessMessage(), ProgressDictionary.getSuccessTitle(pRequestCode),
                    JOptionPane.INFORMATION_MESSAGE);
        }
    }
    // opt2. if the execution result is "FAIL" or else
    else {
        if (pShowSuccessResult == true) {
            JOptionPane.showMessageDialog(UISharedData.getInstance().getCurrentFrame(),
                    observer.getFailMessage(), ProgressDictionary.getErrorTitle(pRequestCode),
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    executorService.shutdown();
    return observer;
}

From source file:org.trnltk.apps.morphology.contextless.parser.CachingMorphologicParserApp.java

@App("Parse sample TBMM Journal with bulk parse")
public void parseTbmmJournal_b0241h_withBulkParse() throws Exception {
    final File tokenizedFile = new File("core/src/test/resources/tokenizer/tbmm_b0241h_tokenized.txt");
    final List<String> lines = Files.readLines(tokenizedFile, Charsets.UTF_8);
    final LinkedList<String> words = new LinkedList<String>();
    final HashSet<String> uniqueWords = new HashSet<String>();
    for (String line : lines) {
        final ArrayList<String> strings = Lists
                .newArrayList(Splitter.on(" ").trimResults().omitEmptyStrings().split(line));
        words.addAll(strings);// w ww  .j  a  v a2 s  . com
        uniqueWords.addAll(strings);
    }

    final int initialL1CacheSize = uniqueWords.size();
    final int maxL1CacheSize = initialL1CacheSize;

    final MorphologicParserCache l1Cache = new LRUMorphologicParserCache(NUMBER_OF_THREADS, initialL1CacheSize,
            maxL1CacheSize);

    final ExecutorService pool = Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    final MorphologicParser[] parsers = new MorphologicParser[NUMBER_OF_THREADS];
    for (int i = 0; i < parsers.length; i++) {
        parsers[i] = new CachingMorphologicParser(new TwoLevelMorphologicParserCache(BULK_SIZE, l1Cache),
                contextlessMorphologicParser, true);
    }

    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    for (int i = 0; i < words.size(); i = i + BULK_SIZE) {
        final MorphologicParser parser = parsers[(i / BULK_SIZE) % NUMBER_OF_THREADS];
        int start = i;
        int end = i + BULK_SIZE < words.size() ? i + BULK_SIZE : words.size();
        final int wordIndex = i;

        final List<String> subWordList = words.subList(start, end);
        pool.execute(new BulkParseCommand(parser, subWordList, wordIndex, false));
    }

    pool.shutdown();
    while (!pool.isTerminated()) {
        System.out.println("Waiting pool to be terminated!");
        pool.awaitTermination(500, TimeUnit.MILLISECONDS);
    }

    stopWatch.stop();

    System.out.println("Total time :" + stopWatch.toString());
    System.out.println("Nr of tokens : " + words.size());
    System.out.println("Avg time : " + (stopWatch.getTime() * 1.0d) / (words.size() * 1.0d) + " ms");
}

From source file:com.linkedin.pinot.integration.tests.BaseClusterIntegrationTest.java

public void setupQueryGenerator(final List<File> avroFiles, ExecutorService executor) {
    executor.execute(new Runnable() {
        @Override/*w  ww  .  jav  a2s  .com*/
        public void run() {
            _queryGenerator = new QueryGenerator(avroFiles, "mytable", "mytable");
        }
    });
}

From source file:org.apache.nifi.controller.scheduling.TestProcessorLifecycle.java

/**
 * Concurrency test that is basically hammers on both stop and start
 * operation validating their idempotency.
 *///from  w ww  .  j  a  va 2 s . com
@Test
@Ignore
public void validateLifecycleOperationOrderWithConcurrentCallsToStartStop() throws Exception {
    fc = this.buildFlowControllerForTest();
    ProcessGroup testGroup = fc.createProcessGroup(UUID.randomUUID().toString());
    this.setControllerRootGroup(fc, testGroup);
    final ProcessorNode testProcNode = fc.createProcessor(TestProcessor.class.getName(),
            UUID.randomUUID().toString());
    testProcNode.setProperties(properties);
    TestProcessor testProcessor = (TestProcessor) testProcNode.getProcessor();

    // sets the scenario for the processor to run
    this.noop(testProcessor);

    final ProcessScheduler ps = fc.getProcessScheduler();
    ExecutorService executor = Executors.newFixedThreadPool(100);
    int startCallsCount = 10000;
    final CountDownLatch countDownCounter = new CountDownLatch(startCallsCount);
    assertTrue(testProcNode.getScheduledState() == ScheduledState.STOPPED);
    final Random random = new Random();
    for (int i = 0; i < startCallsCount / 2; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                LockSupport.parkNanos(random.nextInt(9000000));
                ps.stopProcessor(testProcNode);
                countDownCounter.countDown();
            }
        });
    }
    for (int i = 0; i < startCallsCount / 2; i++) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                LockSupport.parkNanos(random.nextInt(9000000));
                ps.startProcessor(testProcNode);
                countDownCounter.countDown();
            }
        });
    }
    assertTrue(countDownCounter.await(1000000, TimeUnit.MILLISECONDS));
    String previousOperation = null;
    for (String operationName : testProcessor.operationNames) {
        if (previousOperation == null || previousOperation.equals("@OnStopped")) {
            assertEquals("@OnScheduled", operationName);
        } else if (previousOperation.equals("@OnScheduled")) {
            assertEquals("@OnUnscheduled", operationName);
        } else if (previousOperation.equals("@OnUnscheduled")) {
            assertTrue(operationName.equals("@OnStopped") || operationName.equals("@OnScheduled"));
        }
        previousOperation = operationName;
    }
    executor.shutdownNow();
}

From source file:org.kurento.test.base.BrowserTest.java

public Table<Integer, Integer, String> processOcrAndStats(final Map<String, Map<String, Object>> presenter,
        final Map<String, Map<String, Object>> viewer) throws InterruptedException, IOException {

    log.debug("Processing OCR and stats");
    log.trace("Presenter {} : {}", presenter.size(), presenter.keySet());
    log.trace("Viewer {} : {}", viewer.size(), viewer.keySet());

    final Table<Integer, Integer, String> resultTable = HashBasedTable.create();
    final int numRows = presenter.size();
    final int threadPoolSize = Runtime.getRuntime().availableProcessors();
    final ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
    final CountDownLatch latch = new CountDownLatch(numRows);
    final Iterator<String> iteratorPresenter = presenter.keySet().iterator();

    // Process OCR (in parallel)
    for (int i = 0; i < numRows; i++) {
        final int j = i;
        final String key = iteratorPresenter.next();

        executor.execute(new Runnable() {
            @Override/*from w ww  .  java 2s.  co m*/
            public void run() {
                try {
                    String matchKey = containSimilarDate(key, viewer.keySet());
                    if (matchKey != null) {
                        String presenterBase64 = presenter.get(key).get(LATENCY_KEY).toString();
                        String viewerBase64 = viewer.get(matchKey).get(LATENCY_KEY).toString();
                        String presenterDateStr = ocr(presenterBase64);
                        String viewerDateStr = ocr(viewerBase64);
                        String latency = String.valueOf(
                                processOcr(presenterDateStr, viewerDateStr, presenterBase64, viewerBase64));
                        synchronized (resultTable) {
                            if (!resultTable.row(0).containsValue(LATENCY_KEY)) {
                                resultTable.put(0, 0, LATENCY_KEY);
                            }
                            resultTable.put(j + 1, 0, latency);
                        }
                    }
                } finally {
                    latch.countDown();
                }
            }
        });
    }
    latch.await();
    executor.shutdown();

    // Process statistics
    processStats(presenter, resultTable);
    processStats(viewer, resultTable);

    log.debug("OCR + Stats results: {}", resultTable);

    return resultTable;
}

From source file:com.chicm.cmraft.core.NodeConnectionManager.java

public void appendEntries(RaftLog logMgr, long lastApplied) {
    int nServers = getRemoteServers().size();
    if (nServers <= 0) {
        return;/*from  ww w. j a  v  a  2  s .  c  om*/
    }

    ExecutorService executor = Executors.newFixedThreadPool(nServers, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(getRaftNode().getName() + "-AsyncRpcCaller" + (byte) System.currentTimeMillis());
            return t;
        }
    });

    for (ServerInfo server : getRemoteServers()) {
        NodeConnection conn = connections.get(server);
        long startIndex = logMgr.getFollowerMatchIndex(server) + 1;

        LOG.info(getRaftNode().getName() + ": SENDING appendEntries Request TO: " + server);
        Thread t = new Thread(new AsynchronousAppendEntriesWorker(getRaftNode(), conn,
                getRaftNode().getRaftLog(), getRaftNode().getServerInfo(), getRaftNode().getCurrentTerm(),
                logMgr.getCommitIndex(), startIndex - 1, logMgr.getLogTerm(startIndex - 1),
                logMgr.getLogEntries(startIndex, lastApplied), lastApplied));
        t.setDaemon(true);
        executor.execute(t);
    }
}

From source file:org.pentaho.support.bi.server.BISupportUtilityServiceImpl.java

/**
 * loads spring configuration SupportUtil.xml file and creates instance of
 * selected retriever//from w  w  w.  j a va2  s .c o  m
 * 
 * @param args
 * @param prop
 * @return
 */
private boolean executeService(String[] args, final Properties prop) {
    Boolean result = false;
    String SPRING_CONFIG_CLASS = "cofingRetrieverFactory";

    try {

        ApplicationContext context = new ClassPathXmlApplicationContext(BIConstant.SPRING_FILE_NAME);
        final CofingRetrieverFactory factory = (CofingRetrieverFactory) context.getBean(SPRING_CONFIG_CLASS);
        ConfigRetreiver[] config = factory.getConfigRetrevier(args);

        ExecutorService service = Executors.newFixedThreadPool(10);

        // based on the instance created respective retriever is called
        for (final ConfigRetreiver configobj : config) {

            configobj.setBISeverPath(prop);
            configobj.setServerName(selected.getServerName());
            configobj.setInstallType(selected.getInstallType());

            // if file retriever instance set required detail
            if (configobj instanceof FileRetriever) {

                configobj.setBidiXml(selected.getBidiXml());
                configobj.setBidiBatFile(selected.getBidiBatFile());
                configobj.setBidiProrperties(selected.getBidiProrperties());
                configobj.setTomcatXml(selected.getTomcatXml());
            }

            // if browser retriever instance set required detail
            if (configobj instanceof BrowserInfoRetriever) {
                configobj.setBrowserInfo(selected.getBrowserInfo());
            }

            service.execute(new Runnable() {
                public void run() {
                    configobj.readAndSaveConfiguration(prop);
                }
            });

        }

        service.shutdown();
        Thread.sleep(75000);

        // calls ziputility for zip
        if (SupportZipUtil.zipFile(prop)) {

            File file = new File(prop.getProperty(BIConstant.SUPP_INFO_DEST_PATH) + File.separator
                    + prop.getProperty(BIConstant.SUPP_INF_DIR));
            if (file.exists()) {
                delete(file);
            }

            result = true;
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

From source file:com.paniclauncher.workers.InstanceInstaller.java

private void downloadMods(ArrayList<Mod> mods) {
    fireSubProgressUnknown();//from ww w .jav  a 2s. c  o m
    ExecutorService executor = Executors.newFixedThreadPool(8);
    ArrayList<PanicLauncherDownloadable> downloads = getDownloadableMods();
    totalDownloads = downloads.size();

    for (PanicLauncherDownloadable download : downloads) {
        executor.execute(download);
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
    }

    for (Mod mod : mods) {
        if (!downloads.contains(mod) && !isCancelled()) {
            fireTask(App.settings.getLocalizedString("common.downloading") + " " + mod.getFile());
            mod.download(this);
        }
    }
}

From source file:com.paniclauncher.workers.InstanceInstaller.java

private void downloadMojangStuffNew() {
    firePropertyChange("doing", null, App.settings.getLocalizedString("instance.downloadingresources"));
    firePropertyChange("subprogressint", null, null);
    ExecutorService executor = Executors.newFixedThreadPool(8);
    ArrayList<MojangDownloadable> downloads = getNeededResources();
    totalResources = downloads.size();/*from  ww w  .  j  a  v  a2s.co  m*/

    for (MojangDownloadable download : downloads) {
        executor.execute(download);
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
    }
    if (!isCancelled()) {
        fireTask(App.settings.getLocalizedString("instance.organisinglibraries"));
        fireSubProgress(0);
        if (!isServer) {
            String[] libraries = librariesNeeded.split(",");
            for (String libraryFile : libraries) {
                Utils.copyFile(new File(App.settings.getLibrariesDir(), libraryFile), getBinDirectory());
            }
            String[] natives = nativesNeeded.split(",");
            for (String nativeFile : natives) {
                Utils.unzip(new File(App.settings.getLibrariesDir(), nativeFile), getNativesDirectory());
            }
            Utils.delete(new File(getNativesDirectory(), "META-INF"));
        }
        if (isServer) {
            Utils.copyFile(
                    new File(App.settings.getJarsDir(), "minecraft_server." + this.minecraftVersion + ".jar"),
                    getRootDirectory());
        } else {
            Utils.copyFile(new File(App.settings.getJarsDir(), this.minecraftVersion + ".jar"),
                    new File(getBinDirectory(), "minecraft.jar"), true);
        }
    }
}