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.wso2.carbon.sample.http.performance.Http.java

public static void main(String args[]) {
    log.info("Starting WSO2 Http Client");
    url = args[0];//from www.  j  a  v a 2 s. co  m
    username = args[1];
    password = args[2];
    try {
        noOfEvents = Long.parseLong(args[3]);
        elapsedCount = Integer.parseInt(args[4]);
        noOfPublishers = Integer.parseInt(args[5]);
        ExecutorService executor = Executors.newFixedThreadPool(noOfPublishers);
        for (int i = 0; i < noOfPublishers; i++) {
            Runnable publisher = new Http();
            executor.execute(publisher);
        }
        executor.shutdown();

    } catch (NumberFormatException e) {
        log.error("Entered value for no of events is invalid. Please enter an integer", e);
    }
}

From source file:kymr.github.io.future.LoadTest.java

public static void main(String[] args) throws InterruptedException {
    ExecutorService es = Executors.newFixedThreadPool(100);

    RestTemplate rt = new RestTemplate();
    String url = "http://localhost:8080/dr";

    StopWatch main = new StopWatch();
    main.start();//from  www .j  a v a  2 s .c o m

    for (int i = 0; i < 100; i++) {
        es.execute(() -> {
            int idx = counter.addAndGet(1);
            log.info("Thread {}", idx);

            StopWatch sw = new StopWatch();
            sw.start();

            rt.getForObject(url, String.class);

            sw.stop();
            log.info("Elapsed: {} -> {}", idx, sw.getTotalTimeSeconds());
        });
    }

    es.shutdown();
    es.awaitTermination(100, TimeUnit.SECONDS);

    main.stop();
    log.info("Total: {}", main.getTotalTimeSeconds());
}

From source file:MainClass.java

public static void main(String[] args) {
    ExecutorService application = Executors.newFixedThreadPool(2);

    Buffer sharedLocation = new UnsynchronizedBuffer();

    System.out.println("Action\t\tValue\tProduced\tConsumed");
    System.out.println("------\t\t-----\t--------\t--------\n");

    try {//from   w w  w .j a v a2s.c o m
        application.execute(new Producer(sharedLocation));
        application.execute(new Consumer(sharedLocation));
    } catch (Exception exception) {
        exception.printStackTrace();
    }

    application.shutdown(); // terminate application when threads end
}

From source file:com.netcore.hsmart.dataconsumers.SmsDataConsumer.java

public static void main(String args[]) throws Exception {

    ExecutorService executor = Executors.newCachedThreadPool();

    for (int i = 1; i <= COUNTERS; i++) {
        Runnable worker = new SmsDataConsumerRunnable(Integer.toString(i), Integer.toString(GID));
        executor.execute(worker);
    }/*  w  w  w.  j a v a 2s. c om*/
}

From source file:com.netcore.hsmart.dataconsumers.DlrDataConsumer.java

public static void main(String args[]) throws Exception {

    ExecutorService executor = Executors.newCachedThreadPool();

    for (int i = 1; i <= COUNTERS; i++) {
        Runnable worker = new DlrDataConsumerRunnable(Integer.toString(i), Integer.toString(GID));
        executor.execute(worker);
    }/*  w  w w  . j a  va 2 s .co m*/
}

From source file:jsonclient.JsonClient.java

public static void main(String args[]) {

    int EPS = 1;//from  w ww .j  a  va  2  s  .  c o  m
    List<Place> countries = new ArrayList<Place>();
    List<Thread> threads = new ArrayList<Thread>();
    Country country;
    countries = getCountries();
    //CountrySearcher countrySearcher = null;
    Iterator<Place> itrCountry = countries.iterator();
    ExecutorService exec = Executors.newFixedThreadPool(4);

    while (itrCountry.hasNext()) {
        country = new Country(itrCountry.next());
        CountrySearcher cs = new CountrySearcher(country, EPS);
        threads.add(cs.thread);
        exec.execute(cs);
    }

    exec.shutdown();

    for (Thread th : threads)
        try {
            th.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(JsonClient.class.getName()).log(Level.SEVERE, null, ex);
        }

}

From source file:lohbihler.process.Test.java

public static void main(final String[] args) throws Exception {
    final ExecutorService executorService = Executors.newCachedThreadPool();

    final Process process = new ProcessBuilder("cmd").start();
    final InputReader input = new InputReader(process.getInputStream());
    final InputReader error = new InputReader(process.getErrorStream());

    executorService.execute(input);
    executorService.execute(error);//ww w .j  ava 2 s. c o  m
    final OutputStreamWriter out = new OutputStreamWriter(process.getOutputStream());

    Thread.sleep(1000);
    System.out.println("Input: " + input.getInput());
    System.out.println("Error: " + error.getInput());
    System.out.println("Alive: " + process.isAlive());
    System.out.println();

    out.append("PING 1.1.1.1 -n 1 -w 5000\r\n");
    out.flush();

    for (int i = 0; i < 7; i++) {
        Thread.sleep(1000);
        System.out.println("Input: " + input.getInput());
        System.out.println("Error: " + error.getInput());
        System.out.println("Alive: " + process.isAlive());
        System.out.println();
    }

    out.append("PING 1.1.1.1 -n 1 -w 2000\r\n");
    out.flush();

    for (int i = 0; i < 4; i++) {
        Thread.sleep(1000);
        System.out.println("Input: " + input.getInput());
        System.out.println("Error: " + error.getInput());
        System.out.println("Alive: " + process.isAlive());
        System.out.println();
    }

    process.destroy();

    executorService.shutdown();
}

From source file:org.jclouds.examples.blobstore.BlobUploaderMain.java

public static void main(String[] args) throws IOException {

    OptionParser parser = new OptionParser();
    parser.accepts("directory").withRequiredArg().required().ofType(String.class);
    parser.accepts("provider").withRequiredArg().required().ofType(String.class);
    parser.accepts("username").withRequiredArg().required().ofType(String.class);
    parser.accepts("password").withRequiredArg().required().ofType(String.class);
    parser.accepts("region").withRequiredArg().required().ofType(String.class);
    parser.accepts("threads").withRequiredArg().ofType(Integer.TYPE).describedAs("number of parallel threads");
    OptionSet options = null;//w  w w  . ja  v  a  2s .  c  o  m

    try {
        options = parser.parse(args);
    } catch (OptionException e) {
        System.out.println(e.getLocalizedMessage());
        parser.printHelpOn(System.out);
        return;
    }

    if (options.has("threads")) {
        numThreads = Integer.valueOf((String) options.valueOf("numThreads"));
    }

    File rootDir = new File((String) options.valueOf("directory"));
    Collection<File> files = FileUtils.listFiles(rootDir, CanReadFileFilter.CAN_READ, TrueFileFilter.TRUE);
    totalBytes = FileUtils.sizeOfDirectory(rootDir);

    System.out.println("Uploading " + rootDir.getName() + " " + totalBytes / FileUtils.ONE_MB + "MB");

    ExecutorService executor = Executors.newFixedThreadPool(numThreads);

    for (File f : files) {
        BlobUploader b = new BlobUploader((String) options.valueOf("username"),
                (String) options.valueOf("password"), (String) options.valueOf("provider"),
                (String) options.valueOf("region"), f);
        executor.execute(b);
    }
    executor.shutdown();

    try {
        executor.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:fr.tpt.s3.mcdag.scheduling.Main.java

public static void main(String[] args) throws IOException, InterruptedException {

    /* Command line options */
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML Models");
    input.setRequired(true);//from  w w  w .  jav  a 2 s  . c o m
    input.setArgs(Option.UNLIMITED_VALUES); // Sets maximum number of threads to be launched
    options.addOption(input);

    Option outSched = new Option("os", "out-scheduler", false, "Write the scheduling tables into a file.");
    outSched.setRequired(false);
    options.addOption(outSched);

    Option outPrism = new Option("op", "out-prism", false, "Write PRISM model into a file.");
    outPrism.setRequired(false);
    options.addOption(outPrism);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debugOpt = new Option("d", "debug", false, "Enabling debug.");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option preemptOpt = new Option("p", "preempt", false, "Count for preemptions.");
    preemptOpt.setRequired(false);
    options.addOption(preemptOpt);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("MC-DAG framework", options);

        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    boolean bOutSched = cmd.hasOption("out-scheduler");
    boolean bOutPrism = cmd.hasOption("out-prism");
    boolean debug = cmd.hasOption("debug");
    boolean preempt = cmd.hasOption("preempt");
    boolean levels = cmd.hasOption("n-levels");
    int nbFiles = inputFilePath.length;

    int nbJobs = 1;
    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    if (debug)
        System.out.println("[DEBUG] Launching " + inputFilePath.length + " thread(s).");

    int i_files = 0;
    ExecutorService executor = Executors.newFixedThreadPool(nbJobs);

    /* Launch threads to solve allocation */
    while (i_files != nbFiles) {
        SchedulingThread ft = new SchedulingThread(inputFilePath[i_files], bOutSched, bOutPrism, debug,
                preempt);

        ft.setLevels(levels);
        executor.execute(ft);
        i_files++;
    }

    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    System.out.println("[FRAMEWORK Main] DONE");
}

From source file:io.bfscan.clueweb12.BuildWarcTrecIdMapping.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("bz2 Wikipedia XML dump file")
            .create(INPUT_OPTION));/*from  w  ww . ja va 2s.c  om*/
    options.addOption(
            OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("maximum number of documents to index").create(MAX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexing threads")
            .create(THREADS_OPTION));

    options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment"));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BuildWarcTrecIdMapping.class.getCanonicalName(), options);
        System.exit(-1);
    }

    String indexPath = cmdline.getOptionValue(INDEX_OPTION);
    int maxdocs = cmdline.hasOption(MAX_OPTION) ? Integer.parseInt(cmdline.getOptionValue(MAX_OPTION))
            : Integer.MAX_VALUE;
    int threads = cmdline.hasOption(THREADS_OPTION) ? Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION))
            : DEFAULT_NUM_THREADS;

    long startTime = System.currentTimeMillis();

    String path = cmdline.getOptionValue(INPUT_OPTION);
    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    Directory dir = FSDirectory.open(new File(indexPath));
    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_43, ANALYZER);
    config.setOpenMode(OpenMode.CREATE);

    IndexWriter writer = new IndexWriter(dir, config);
    LOG.info("Creating index at " + indexPath);
    LOG.info("Indexing with " + threads + " threads");

    FileInputStream fis = null;
    BufferedReader br = null;

    try {
        fis = new FileInputStream(new File(path));
        byte[] ignoreBytes = new byte[2];
        fis.read(ignoreBytes); // "B", "Z" bytes from commandline tools
        br = new BufferedReader(new InputStreamReader(new CBZip2InputStream(fis), "UTF8"));

        ExecutorService executor = Executors.newFixedThreadPool(threads);
        int cnt = 0;
        String s;
        while ((s = br.readLine()) != null) {
            Runnable worker = new AddDocumentRunnable(writer, s);
            executor.execute(worker);

            cnt++;
            if (cnt % 1000000 == 0) {
                LOG.info(cnt + " articles added");
            }
            if (cnt >= maxdocs) {
                break;
            }
        }

        executor.shutdown();
        // Wait until all threads are finish
        while (!executor.isTerminated()) {
        }

        LOG.info("Total of " + cnt + " articles indexed.");

        if (cmdline.hasOption(OPTIMIZE_OPTION)) {
            LOG.info("Merging segments...");
            writer.forceMerge(1);
            LOG.info("Done!");
        }

        LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        writer.close();
        dir.close();
        out.close();
        br.close();
        fis.close();
    }
}