Example usage for java.util.concurrent ExecutorService submit

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

Introduction

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

Prototype

Future<?> submit(Runnable task);

Source Link

Document

Submits a Runnable task for execution and returns a Future representing that task.

Usage

From source file:de.citec.csra.highlight.HighlightService.java

public static void main(String[] args)
        throws InitializeException, RSBException, InterruptedException, ParseException {

    Options opts = new Options();
    opts.addOption("scope", true, "RSB scope for highlight targets.\nDefault: '" + scope + "'");
    opts.addOption("server", true, "RSB server for configuration, e.g., tokens.\nDefault: '" + cfg + "'");
    opts.addOption("help", false, "Print this help and exit");

    String footer = null;/*www  .ja  v  a 2s . c  om*/
    //      String footer = "\nThe following sub-scopes are registered automatically:\n"
    //            + "\n.../preset for color presets:\n" + Arrays.toString(ColorConfig.values())
    //            + "\n.../color for color values:\n" + "HSV (comma separated)"
    //            + "\n.../power for power states:\n" + Arrays.toString(PowerState.State.values())
    //            + "\n.../history for history commands:\n" + Arrays.toString(ColorHistory.values());

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(opts, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("csra-highlight-service [OPTION...]", "where OPTION includes:", opts, footer);
        System.exit(0);
    }

    if (System.getenv().containsKey(SCOPEVAR)) {
        scope = System.getenv(SCOPEVAR);
    }

    String s = cmd.getOptionValue("scope");
    if (s != null) {
        scope = s;
    }
    scope = scope.replaceAll("/$", "");

    String c = cmd.getOptionValue("cfg");
    if (c != null) {
        cfg = c;
    }
    cfg = cfg.replaceAll("/$", "");

    Defaults.loadDefaults();
    ExecutorService exec = Executors.newFixedThreadPool(2);

    exec.submit(() -> {
        try {
            ConfigServer cfgServer = new ConfigServer(cfg);
            cfgServer.execute();
        } catch (RSBException ex) {
            LOG.log(Level.SEVERE, "Config server failed", ex);
        }
    });

    exec.submit(() -> {
        try {
            TaskServer server = new TaskServer(scope, new HighlightTaskHandler());
            server.execute();
        } catch (RSBException | InterruptedException ex) {
            LOG.log(Level.SEVERE, "Task server failed", ex);
        }
    });

}

From source file:CallableTask.java

public static void main(String[] args) throws Exception {
    // Get an executor with three threads in its thread pool
    ExecutorService exec = Executors.newFixedThreadPool(3);
    CallableTask task = new CallableTask(1);
    // Submit the callable task to executor
    Future<Integer> submittedTask = exec.submit(task);

    Integer result = submittedTask.get();
    System.out.println("Task's total  sleep time: " + result + "  seconds");
    exec.shutdown();/*  w w  w . j a v  a  2s .  co  m*/
}

From source file:PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override//from www  .  j ava 2 s.  c  om
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8099/query");
                    CloseableHttpResponse res;
                    while (true) {
                        String query = QUERIES[random.nextInt(numQueries)];
                        post.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override/*from  www. jav  a 2 s  .co  m*/
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
                    post.addHeader("content-type", "application/json");
                    CloseableHttpResponse res;
                    while (true) {
                        try (BufferedReader reader = new BufferedReader(new FileReader(
                                QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) {
                            int length = reader.read(BUFFER);
                            post.setEntity(new StringEntity(new String(BUFFER, 0, length)));
                        }
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:Main.java

public static void main(final String[] args) throws Exception {
    Random RND = new Random();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    List<Future<String>> results = new ArrayList<>(10);
    for (int i = 0; i < 10; i++) {
        results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
    }//from w w  w  .  ja v  a 2  s. c om
    es.shutdown();
    while (!results.isEmpty()) {
        Iterator<Future<String>> i = results.iterator();
        while (i.hasNext()) {
            Future<String> f = i.next();
            if (f.isDone()) {
                System.out.println(f.get());
                i.remove();
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    System.out.println("Thread pool size = " + MAX_THREADS);
    ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
    Future previousFuture = null;
    for (int i = 0; i < MAX_THREADS; i++) {
        JobRunnable job = new JobRunnable(i, previousFuture);
        previousFuture = executor.submit(job);
    }/*w  w w.  j a  va 2 s .co  m*/
    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    System.out.println("Program done.");
}

From source file:com.fjn.helper.frameworkex.apache.commons.pool.connectionPool.ConnectionManager.java

public static void main(String[] args) {
    final ConnectionManager mgr = new ConnectionManager();
    mgr.connFactory = new ConnectionFactory();
    mgr.connFactory.setDriverClass("com.mysql.jdbc.Driver");
    mgr.connFactory.setPassword("mysql");
    mgr.connFactory.setUsername("mysql");
    mgr.connFactory.setUrl("url:localhost:3306"); // ?URL

    mgr.initConnectionPool(1000, 50, 5, 1000 * 60);
    mgr.pool = mgr.connPoolFactory.createPool();

    final AtomicInteger count = new AtomicInteger(0);

    int threadNum = Runtime.getRuntime().availableProcessors();
    ExecutorService client = Executors.newFixedThreadPool(threadNum);
    for (int i = 0; i < threadNum; i++) {
        client.submit(new Runnable() {
            @Override/*w  w  w.  j av a 2  s. c  o  m*/
            public void run() {
                while (true && count.get() < 100) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    Connection connection = null;

                    try {
                        connection = (Connection) mgr.pool.borrowObject();
                        try {

                            int value = count.incrementAndGet();
                            if (value < 100) {
                                String threadName = Thread.currentThread().getName();

                                int activeNum = mgr.pool.getNumActive();
                                int idleNum = mgr.pool.getNumIdle();
                                String content = "ThreadName: " + threadName + "\t SQL: "
                                        + "insert into tableA ( ct ) values ('" + value + "'); \t activeNum="
                                        + activeNum + "\t idleNum=" + idleNum;
                                System.out.println(content);
                            }

                        } catch (Exception e) {
                            mgr.pool.invalidateObject(connection);
                            connection = null;
                        } finally {
                            // make sure the object is returned to the pool
                            if (null != connection) {
                                mgr.pool.returnObject(connection);
                            }
                        }
                    } catch (Exception e) {
                        // failed to borrow an object
                    }

                }
            }
        });
    }
}

From source file:RunnableTask.java

public static void main(String[] args) {
    final int THREAD_COUNT = 3;
    final int LOOP_COUNT = 3;
    final int TASK_COUNT = 5;

    // Get an executor with three threads in its thread pool
    ExecutorService exec = Executors.newFixedThreadPool(THREAD_COUNT);

    // Create five tasks and submit them to the executor
    for (int i = 1; i <= TASK_COUNT; i++) {
        RunnableTask task = new RunnableTask(i, LOOP_COUNT);
        exec.submit(task);
    }//from   w w  w.j a va 2 s. c o m
    exec.shutdown();
}

From source file:com.linkedin.pinotdruidbenchmark.PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(/* w ww.j av a 2s  .  c om*/
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        String query = new BufferedReader(new FileReader(queryFiles[i])).readLine();
        httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:org.wso2.carbon.sample.tfl.TflEventDispatcher.java

public static void main(String[] args) {
    EventDispatcher trafficDisruptionData = new EventDispatcher(
            "http://localhost:9763/endpoints/GpsDataOverHttpTrafficStream", "tfl-traffic-data.out", 1000);
    EventDispatcher busTrafficData = new EventDispatcher(
            "http://localhost:9763/endpoints/BusTrafficCsvReceiver", "tfl-bus-data.out", 50);
    EventDispatcher busStopData = new EventDispatcher("http://localhost:9763/endpoints/BusTrafficCsvReceiver",
            "tfl-bus-stop-data.out", 5);
    EventDispatcher timeTableData = new EventDispatcher("http://localhost:9763/endpoints/TimeTableCsvReceiver",
            "tfl-timetable-data.out", 5);
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    // executorService.submit(trafficDisruptionData);
    // timeTableData.run();
    // busStopData.run();
    executorService.submit(busTrafficData);
}