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:org.pepstock.jem.node.NodeInfoUtility.java

/**
 * Drains the node itself/*from   w  ww.j  av a 2s. c o m*/
 */
public static void drain() {
    // creates the distributed task to drain itself
    DistributedTask<ExecutionResult> task = new DistributedTask<ExecutionResult>(new Drain(),
            Main.getHazelcast().getCluster().getLocalMember());
    ExecutorService executorService = Main.getHazelcast().getExecutorService();
    task.setExecutionCallback(new GenericCallBack());
    executorService.execute(task);
}

From source file:org.pepstock.jem.node.NodeInfoUtility.java

/**
 * Starts the node//from  w w  w  .  j a v  a 2 s .co m
 */
public static void start() {
    // creates the distributed task to start itself
    DistributedTask<ExecutionResult> task = new DistributedTask<ExecutionResult>(new Start(),
            Main.getHazelcast().getCluster().getLocalMember());
    ExecutorService executorService = Main.getHazelcast().getExecutorService();
    task.setExecutionCallback(new GenericCallBack());
    executorService.execute(task);
}

From source file:com.laudandjolynn.mytv.Main.java

/**
 * ??/*from w  w  w  . j  a v  a  2  s. c om*/
 */
private static void initDbData(final MyTvData data) {
    final TvService tvService = new TvServiceImpl();
    makeCache(tvService);

    // ??
    ExecutorService executorService = Executors.newSingleThreadExecutor(
            new BasicThreadFactory.Builder().namingPattern("Mytv_Crawl_Task_%d").build());
    executorService.execute(new Runnable() {

        @Override
        public void run() {
            runCrawlTask(data, tvService);
        }
    });
    executorService.shutdown();
    // ??
    logger.info("create everyday crawl task.");
    createEverydayCron(data, tvService);
}

From source file:example.rhino.DynamicScopesWithHandlebars.java

private static void runScripts(Context cx, Script script, ExecutorService executor) {
    ScriptableObject sharedScope = cx.initStandardObjects(null, true);
    script.exec(cx, sharedScope);/* w  ww  . ja v a 2s.c  om*/

    Runnable[] run = new Runnable[NUM_THREAD];
    for (int i = 0; i < NUM_THREAD; i++) {

        String source2 = "Handlebars.precompile(template)";

        run[i] = new PerThread(sharedScope, source2, i);
    }
    for (int i = 0; i < NUM_THREAD; i++) {
        executor.execute(run[i]);
    }

    executor.shutdown();

    try {
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

From source file:org.openhab.binding.network.service.NetworkService.java

/**
 * Starts the DiscoveryThread for each IP on the Networks
 *
 * @param allNetworkIPs//from   www.  j  a v  a 2s  . c  om
 */
private static void startDiscovery(final LinkedHashSet<String> networkIPs,
        final DiscoveryCallback discoveryCallback, ScheduledExecutorService scheduledExecutorService) {
    final int PING_TIMEOUT_IN_MS = 500;
    ExecutorService executorService = Executors
            .newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 10);

    for (Iterator<String> it = networkIPs.iterator(); it.hasNext();) {
        final String ip = it.next();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                if (ip != null) {
                    try {
                        if (Ping.checkVitality(ip, 0, PING_TIMEOUT_IN_MS)) {
                            discoveryCallback.newDevice(ip);
                        }
                    } catch (IOException e) {
                    }
                }
            }
        });
    }
    try {
        executorService.awaitTermination(PING_TIMEOUT_IN_MS * networkIPs.size(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
    }
    executorService.shutdown();
}

From source file:eu.stratosphere.nephele.streaming.taskmanager.chaining.TaskChain.java

public static TaskChain mergeAndAnnounceChains(List<TaskChain> subchains, ExecutorService backgroundWorkers,
        final QosReporterConfigCenter configCenter) {

    final TaskChain mergedChain = new TaskChain();

    for (TaskChain subchain : subchains) {
        mergedChain.tasksInChain.addAll(subchain.tasksInChain);
    }/* ww  w.ja  v  a2s .co m*/

    mergedChain.fixTasksChainedStatus();
    mergedChain.taskControlFlowsUnderManipulation.set(true);

    backgroundWorkers.execute(new Runnable() {
        @Override
        public void run() {
            try {
                ChainingUtil.chainTaskThreads(mergedChain, configCenter);
            } catch (Exception e) {
                LOG.error("Error during chain construction.", e);
            } finally {
                mergedChain.taskControlFlowsUnderManipulation.set(false);
            }
        }
    });

    return mergedChain;
}

From source file:agileinterop.AgileInterop.java

private static JSONObject getPSRList(String body)
        throws ParseException, InterruptedException, java.text.ParseException, Exception {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONObject jsonBody = (JSONObject) parser.parse(body);

    Date startDateOriginated = new SimpleDateFormat("MM/dd/yyyy")
            .parse(jsonBody.get("startDateOriginated").toString());
    Date endDateOriginated = new SimpleDateFormat("MM/dd/yyyy")
            .parse(jsonBody.get("endDateOriginated").toString());

    List<String> data = new ArrayList<>();

    class getPSRListForDate implements Runnable {
        private Date dateOriginated;
        private List<String> data;

        public getPSRListForDate(Date dateOriginated, List<String> data) {
            this.dateOriginated = dateOriginated;
            this.data = data;
        }/*from www .  j a v a2s.  c  om*/

        public getPSRListForDate(List<String> data) {
            this.data = data;
        }

        @Override
        public void run() {
            try {
                String dateOriginatedString = new SimpleDateFormat("MM/dd/yyyy").format(dateOriginated);

                Long startTime = System.currentTimeMillis();

                IQuery query = (IQuery) Agile.session.createObject(IQuery.OBJECT_TYPE,
                        "Product Service Requests");

                String criteria = "[Cover Page.Date Originated] == '" + dateOriginatedString
                        + " 12:00:00 AM GMT' AND "
                        + "[Cover Page.Type] IN ('Customer Complaint', 'Customer Inquiry', 'Partner Complaint', "
                        + "'Reportable Malfunction / Adverse Event', 'Ancillary Devices & Applications', 'Distributors / Partners', "
                        + "'MDR Decision Tree', 'Investigation Report - No RGA', 'Investigation Report - RGA')";
                query.setCriteria(criteria);

                query.setResultAttributes(new Integer[] { 4856 }); // 4856 = Object ID of [Cover Page.PSR Number]

                ITable queryResults = query.execute();
                queryResults.setPageSize(5000);

                ITwoWayIterator tableIterator = queryResults.getTableIterator();
                while (tableIterator.hasNext()) {
                    IRow row = (IRow) tableIterator.next();
                    data.add(row.getCell(4856).toString()); // 4856 = Object ID of [Cover Page.PSR Number]
                }

                Long endTime = System.currentTimeMillis();

                String logMessage = String.format("getPSRList: Query for %s executed in %d milliseconds",
                        new SimpleDateFormat("yyyy-MM-dd").format(dateOriginated), endTime - startTime);
                System.out.println(logMessage);
            } catch (APIException ex) {
                Logger.getLogger(AgileInterop.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    if (startDateOriginated.after(endDateOriginated)) {
        throw new Exception("startDateOriginated is after endDateOriginated. This makes no sense, silly.");
    }

    synchronized (data) {
        Date currentDateOriginated = startDateOriginated;

        ExecutorService executor = Executors.newFixedThreadPool(6);
        do {
            executor.execute(new Thread(new getPSRListForDate(currentDateOriginated, data)));

            Calendar c = Calendar.getInstance();
            c.setTime(currentDateOriginated);
            c.add(Calendar.DATE, 1);

            currentDateOriginated = c.getTime();
        } while (currentDateOriginated.before(endDateOriginated)
                | currentDateOriginated.equals(endDateOriginated));

        executor.shutdown();
        while (!executor.isTerminated()) {
        }
    }

    JSONObject obj = new JSONObject();
    obj.put("data", data);
    return obj;
}

From source file:com.laudandjolynn.mytv.Main.java

/**
 * ??//from ww w  .  ja v a2 s.  c om
 * 
 * @param executorService
 * @param date
 * @param tvService
 */
private static void crawlAllProgramTable(List<TvStation> stationList, ExecutorService executorService,
        final String date, TvService tvService) {
    int size = stationList == null ? 0 : stationList.size();
    for (int i = 0; i < size; i++) {
        final TvStation tvStation = stationList.get(i);
        executorService.execute(new Runnable() {

            @Override
            public void run() {
                CrawlAction.getIntance().queryProgramTable(tvStation, date);
            }
        });
    }
}

From source file:org.apache.vxquery.xtest.util.DiskPerformance.java

static <T> void runThreadTest(Class<T> testType, DiskPerformance dp, int threads, int bufferSize)
        throws InstantiationException, IllegalAccessException {
    ExecutorService es = Executors.newCachedThreadPool();
    ArrayList<IDiskTest> threadTests = new ArrayList<IDiskTest>();
    for (int i = 0; i < threads; ++i) {
        threadTests.add((IDiskTest) testType.newInstance());
    }/*  www.  j a  va2  s.c  o  m*/
    for (IDiskTest test : threadTests) {
        test.setFile(dp.getNextFile());
        test.setBufferSize(bufferSize);
        test.setParser(dp.getNewParser().first);
        es.execute((Runnable) test);
    }
    es.shutdown();
    try {
        es.awaitTermination(60, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    //        System.out.println("Completed thread batch: " + new Date());
}

From source file:org.openmrs.logic.util.LogicUtil.java

/**
 * Generic method to fork a new command for the operating system to run.
 * /*  w ww . ja v  a2s  . c  om*/
 * @param commands the command and the parameters
 * @param workingDirectory the directory where the commands should be invoked
 * @return true when the command executed succesfully.
 */
public static final boolean executeCommand(String[] commands, File workingDirectory) {

    boolean executed = false;
    try {
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM)
            process = runtime.exec(commands, null, workingDirectory);
        else
            process = runtime.exec(commands);

        ExecutorService executorService = Executors.newCachedThreadPool();

        StreamHandler errorHandler = new StreamHandler(process.getErrorStream(), "ERROR");
        StreamHandler outputHandler = new StreamHandler(process.getInputStream(), "OUTPUT");

        if (executorService == null)
            executorService = Executors.newCachedThreadPool();

        executorService.execute(errorHandler);
        executorService.execute(outputHandler);

        int exitValue = process.waitFor();
        log.info("Process execution completed with exit value: " + exitValue + " ...");

        executed = true;
    } catch (Exception e) {
        log.error("Error generated", e);
    }

    return executed;
}