Example usage for java.util.concurrent ThreadPoolExecutor submit

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

Introduction

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

Prototype

public Future<?> submit(Runnable task) 

Source Link

Usage

From source file:ReplaceWorker.java

public static void main(String[] args) {
    map.put("key", 1);
    Main test = new Main();
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 100, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(1000));
    for (int i = 0; i < 100; i++) {
        threadPool.submit(new MergeWorker());
    }//from   w  w w.  j  a  v  a  2 s .  c  om
    awaitTermination(threadPool);
    System.out.println(test.map.get("key"));

    map.put("key", 1);
    threadPool = new ThreadPoolExecutor(10, 10, 100, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000));
    for (int i = 0; i < 100; i++) {
        threadPool.submit(new ReplaceWorker());
    }
    awaitTermination(threadPool);
    System.out.println(test.map.get("key"));
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(48);
    ThreadPoolExecutor testExecutor = new ThreadPoolExecutor(6, 10, 1, TimeUnit.SECONDS, blockingQueue);
    List<Future<String>> futures = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
        Future<String> testFuture = testExecutor.submit(new MyCallable(i));
        futures.add(testFuture);/*  ww  w  .  j a  v a 2 s.com*/
    }
    for (Future<String> testFuture : futures) {
        System.out.println("Output Returned is : " + testFuture.get());
    }
}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

public static void main(String[] args) throws Exception {
    // Let's use some colors :)
    //        AnsiConsole.systemInstall();
    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = null;//from   w ww  .jav  a2s  .c o  m
    try {
        cli = cliParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        printHelp();
    }
    if (!cli.hasOption("s")) {
        printHelp();
    }

    String sourcePattern;
    if (cli.hasOption("p")) {
        sourcePattern = cli.getOptionValue("p");
    } else {
        sourcePattern = DEFAULT_SOURCE_PATTERN;
    }

    String defaultAnswer;
    if (cli.hasOption("default-answer")) {
        defaultAnswer = cli.getOptionValue("default-answer");
    } else {
        defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER;
    }

    boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y");
    boolean quiet = cli.hasOption("q");
    boolean testWrite = cli.hasOption("t");
    Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath();
    // Since we use IO we will have some blocking threads hanging around
    int threadCount = Runtime.getRuntime().availableProcessors() * 2;
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();

    findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> {
        // We can't really find usages of widget vars that use EL expressions :(
        if (widgetVarLocation.widgetVar.contains("#")) {
            unusedOrAmbiguous.add(widgetVarLocation);
            return;
        }

        try {
            FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern,
                    sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> {
                        findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages,
                                unusedOrAmbiguous);
                        return null;
                    })));

            Files.walkFileTree(sourceDirectory, visitor);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    awaitAll(futures);

    new TreeSet<>(skippedUsages).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col "
                + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'");
        System.out.println("\t" + previous);
    });

    Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>();

    new TreeSet<>(foundUsages).forEach(widgetUsage -> {
        WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null);
        List<WidgetVarLocation> writtenList = written.get(key);
        int existing = writtenList == null ? 0 : writtenList.size();
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED)
                .a("PF('" + widgetUsage.widgetVar + "')").reset().toString());
        System.out
                .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + next);
        System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: ");

        String input;

        if (quiet) {
            input = "";
            System.out.println();
        } else {
            try {
                do {
                    input = in.readLine();
                } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input)
                        && !"n".equalsIgnoreCase(input));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (input == null) {
            System.out.println("Aborted!");
        } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) {
            System.out.println("Replaced!");
            System.out.print("\t");
            if (writtenList == null) {
                writtenList = new ArrayList<>();
                written.put(key, writtenList);
            }

            writtenList.add(widgetUsage);
            List<String> lines;
            try {
                lines = Files.readAllLines(widgetUsage.location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            try (OutputStream os = testWrite ? new ByteArrayOutputStream()
                    : Files.newOutputStream(widgetUsage.location);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
                String line;

                for (int i = 0; i < lines.size(); i++) {
                    int lineNr = i + 1;
                    line = lines.get(i);

                    if (lineNr == widgetUsage.lineNr) {
                        int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6);
                        int end = begin + widgetUsage.widgetVar.length();
                        String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')",
                                false);

                        if (testWrite) {
                            System.out.println(newLine);
                        } else {
                            pw.println(newLine);
                        }
                    } else {
                        if (!testWrite) {
                            pw.println(line);
                        }
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            System.out.println("Skipped!");
        }
    });

    new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr
                + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + previous);
    });

    threadPool.shutdown();
}

From source file:com.l2jfree.util.concurrent.L2ThreadPool.java

public static Future<?> submit(Runnable r) {
    r = ExecuteWrapper.wrap(r);/*from   w w w.  j a  v a 2  s .  c om*/

    final ThreadPoolExecutor tpe = getRandomPool(_instantPools);
    final Future<?> f = tpe.submit(r);

    return new FutureWrapper(f);
}

From source file:com.l2jfree.util.concurrent.L2ThreadPool.java

public static Future<?> submitLongRunning(Runnable r) {
    r = ExecuteWrapper.wrapLongRunning(r);

    final ThreadPoolExecutor tpe = getRandomPool(_longRunningPools);
    final Future<?> f = tpe.submit(r);

    return new FutureWrapper(f);
}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

private static Stream<WidgetVarLocation> findWidgetVars(Path sourceDirectory, String sourcePattern,
        ThreadPoolExecutor threadPool) throws IOException {
    BlockingQueue<WidgetVarLocation> pipe = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();
    Files.walkFileTree(sourceDirectory, new FileActionVisitor(sourceDirectory, sourcePattern,
            sourceFile -> futures.add(threadPool.submit(() -> {
                try (BufferedReader br = Files.newBufferedReader(sourceFile, StandardCharsets.UTF_8)) {
                    int lineNr = 0;
                    String line;/*from   www .java 2 s.  co  m*/
                    while ((line = br.readLine()) != null) {
                        lineNr++;

                        if (line.contains("widgetVar=\"")) {
                            int startIndex = line.indexOf("widgetVar=\"") + "widgetVar=\"".length();
                            int endIndex = line.indexOf('"', startIndex);
                            String var = line.substring(startIndex, endIndex);
                            WidgetVarLocation widgetVar = new WidgetVarLocation(var, sourceFile, lineNr,
                                    startIndex, line);

                            pipe.add(widgetVar);
                        }
                    }
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }))));

    return StreamSupport.stream(new PipeSpliterator(pipe, futures), true);
}

From source file:logicProteinHypernetwork.analysis.complexes.SPINComplexPrediction.java

/**
 * Refine plain network based predicted complexes based on the protein 
 * hypernetwork with a certain ComplexRefinement instance.
 * /*  ww w  . j av  a 2s .  c  o m*/
 * @param naiveComplexes the plain network based complexes
 * @param complexRefinement the instance of ComplexRefinement
 */
protected void refinement(final Collection<Complex> naiveComplexes,
        final SPINComplexRefinement complexRefinement) {

    ThreadPoolExecutor threads = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadCount);

    for (final Complex c : naiveComplexes) {
        threads.submit(new RefineComplex(c, complexRefinement));
    }

    threads.shutdown();
    try {
        threads.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
    } catch (InterruptedException ex) {
        System.err.println(ex);
    }

    Set<Complex> unique = new HashSet<Complex>(complexes);
    complexes.clear();
    complexes.addAll(unique);

    //System.out.println("Refined to " + complexes.size() + " complexes");
}

From source file:org.esigate.test.cases.PerformanceTestCase.java

/**
 * Execute la tache avec plusieurs Threads
 * //from  ww w  .  java 2 s.  c o  m
 * @param request
 * @return
 * @throws Exception
 */
private long execute(HttpGetRequestRunnable request, int numberOfRequests, int threads) throws Exception {
    connectionManager = new PoolingHttpClientConnectionManager();
    httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).setMaxConnTotal(threads)
            .setMaxConnPerRoute(threads).setDefaultRequestConfig(
                    RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build())
            .build();
    // Warm up
    request.run();

    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threads, threads, 5, TimeUnit.SECONDS, queue);

    long start = System.currentTimeMillis();
    threadPool.prestartAllCoreThreads();
    for (int i = 0; i < numberOfRequests; i++) {
        threadPool.submit(request);
    }
    threadPool.shutdown();

    // wait maximum 20 s
    threadPool.awaitTermination(200, TimeUnit.SECONDS);
    connectionManager.shutdown();

    if (request.exception != null) {
        throw new AssertionFailedError(
                "Exception for request " + request.url + " after " + request.count + " requests",
                request.exception);
    }
    if (threadPool.getCompletedTaskCount() < threadPool.getTaskCount()) {
        // All task were not executed
        String msg = request.url + " : Only " + threadPool.getCompletedTaskCount() + "/"
                + threadPool.getTaskCount() + " have been renderered " + " => Maybe a performance issue";
        threadPool.shutdownNow();
        fail(msg);
    }

    long end = System.currentTimeMillis();
    long execTime = end - start;
    LOG.debug("Executed request " + request.url + " " + numberOfRequests + " times with " + threads
            + " threads in " + execTime + "ms");
    return execTime;

}

From source file:org.obm.opush.PingHandlerTest.java

private Future<Document> queuePingCommand(final OPClient opClient, final OpushUser user,
        ThreadPoolExecutor threadPoolExecutor) {
    return threadPoolExecutor.submit(new Callable<Document>() {
        @Override/*from   www  .  j a  va 2s  .com*/
        public Document call() throws Exception {
            Document document = buildPingCommand(5, user.hashCode());
            return opClient.postXml("Ping", document, "Ping", null, false);
        }
    });
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void maxUsage_SingleThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);//  w  ww  . ja  va 2  s  .co  m
    e.prestartAllCoreThreads();

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("MAX Singlethreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("MAX Singlethreaded overall usage: " + actualUsage);
}