List of usage examples for java.util.concurrent ThreadPoolExecutor prestartAllCoreThreads
public int prestartAllCoreThreads()
From source file:Test.java
public static void main(String[] args) throws InterruptedException { BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(); for (int i = 0; i < 10; i++) { final int localI = i; queue.add(new Runnable() { public void run() { doExpensiveOperation(localI); }// ww w. j ava 2 s. com }); } ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, queue); executor.prestartAllCoreThreads(); executor.shutdown(); executor.awaitTermination(100000, TimeUnit.SECONDS); }
From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java
public static void main(String[] args) throws Exception { Parser parser = new PosixParser(); Options options = new Options(); options.addOption("r", "repo", true, "Repository type to search: local|central"); options.addOption("c", "client-concurrency", true, "Max threads to allow each client tester to run tests, defaults to 10"); options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5"); options.addOption("m", "max-time", true, "Max time (in minutes) to allow tests to complete, defaults to 10"); options.addOption("v", "version", false, "Print version and exit"); options.addOption("h", "help", false, "This help text"); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { System.out.println(options); System.exit(0);//from w w w . jav a 2 s .c o m } if (commandLine.hasOption("v")) { System.out.println("How the hell should I know?"); System.exit(0); } // 1. Find all testers in given repos List<RepoSearcher> repoSearchers = new ArrayList<>(); for (String repo : commandLine.getOptionValues("r")) { if ("local".equals(repo.toLowerCase())) { repoSearchers.add(new LocalRepoSearcher()); } else if ("central".equals(repo.toLowerCase())) { repoSearchers.add(new CentralRepoSearcher()); } else { System.err.println("Unrecognized repo: " + repo); System.err.println(options); System.exit(1); } } int clientConcurrency = 10; if (commandLine.hasOption("c")) { try { clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c")); } catch (NumberFormatException nfe) { System.err.println( "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'"); System.exit(1); } } int testConcurrency = 5; if (commandLine.hasOption("t")) { try { testConcurrency = Integer.parseInt(commandLine.getOptionValue("t")); } catch (NumberFormatException nfe) { System.err.println( "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'"); System.exit(1); } } int maxMinutes = 10; if (commandLine.hasOption("m")) { try { maxMinutes = Integer.parseInt(commandLine.getOptionValue("m")); } catch (NumberFormatException nfe) { System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'"); System.exit(1); } } Properties clientProps = new Properties(); clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency)); File baseRunDir = new File(System.getProperty("user.dir") + "/run"); baseRunDir.mkdirs(); File tmpDir = new File(baseRunDir, "jars"); tmpDir.mkdirs(); List<ServerRunner> serverRunners = new ArrayList<>(); List<ClientRunner> clientRunners = new ArrayList<>(); for (RepoSearcher searcher : repoSearchers) { List<File> jars = searcher.findAndCache(tmpDir); for (File f : jars) { ServerRunner serverRunner = new ServerRunner(f, baseRunDir); System.out.println("Found tester: " + serverRunner.getVersion()); serverRunners.add(serverRunner); clientRunners.add(new ClientRunner(f, baseRunDir, clientProps)); } } // 2. Start servers and collect ports System.out.println(); System.out.println("Starting " + serverRunners.size() + " servers..."); for (ServerRunner server : serverRunners) { server.startServer(); } System.out.println(); List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size()); for (ServerRunner server : serverRunners) { for (ClientRunner client : clientRunners) { tests.add(new TestCombo(server, client)); } } System.out.println("Enqueued " + tests.size() + " test combos to run..."); long startTime = System.currentTimeMillis(); // 3. Run every client against every server, collecting results BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size()); ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000, TimeUnit.MILLISECONDS, workQueue); service.prestartAllCoreThreads(); workQueue.addAll(tests); while (!workQueue.isEmpty()) { Thread.sleep(1000); } service.shutdown(); service.awaitTermination(maxMinutes, TimeUnit.MINUTES); long endTime = System.currentTimeMillis(); long totalTimeSecs = Math.round((endTime - startTime) / 1000.0); for (ServerRunner server : serverRunners) { server.shutdownServer(); } System.out.println(); System.out.println("======="); System.out.println("Results"); System.out.println("-------"); // print a summary int totalTests = 0; int totalSuccess = 0; for (TestCombo combo : tests) { String clientVer = combo.getClientVersion(); String serverVer = combo.getServerVersion(); String results = combo.getClientResults(); ObjectMapper mapper = new ObjectMapper(new JsonFactory()); JsonNode node = mapper.reader().readTree(results); JsonNode resultsArray = node.get("results"); int numTests = resultsArray.size(); int numSuccess = 0; for (int i = 0; i < numTests; i++) { if ("success".equals(resultsArray.get(i).get("result").asText())) { numSuccess++; } } totalSuccess += numSuccess; totalTests += numTests; System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds"); } System.out.println("-------"); System.out.println( "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds"); FileWriter out = new FileWriter("results.json"); PrintWriter pw = new PrintWriter(out); // 4. Output full results pw.println("{\n \"results\": ["); for (TestCombo combo : tests) { combo.emitResults(pw, " "); } pw.println(" ],"); pw.println(" \"servers\": ["); for (ServerRunner server : serverRunners) { server.emitInfo(pw, " "); } pw.println(" ],"); pw.close(); }
From source file:org.caffinitas.ohc.benchmark.BenchmarkOHC.java
public static void main(String[] args) throws Exception { Locale.setDefault(Locale.ENGLISH); Locale.setDefault(Locale.Category.FORMAT, Locale.ENGLISH); try {//from w w w . j a v a2 s . c om CommandLine cmd = parseArguments(args); String[] warmUp = cmd.getOptionValue(WARM_UP, "15,5").split(","); int warmUpSecs = Integer.parseInt(warmUp[0]); int coldSleepSecs = Integer.parseInt(warmUp[1]); int duration = Integer.parseInt(cmd.getOptionValue(DURATION, "60")); int cores = Runtime.getRuntime().availableProcessors(); if (cores >= 8) cores -= 2; else if (cores > 2) cores--; int threads = Integer.parseInt(cmd.getOptionValue(THREADS, Integer.toString(cores))); long capacity = Long.parseLong(cmd.getOptionValue(CAPACITY, "" + (1024 * 1024 * 1024))); int hashTableSize = Integer.parseInt(cmd.getOptionValue(HASH_TABLE_SIZE, "0")); int segmentCount = Integer.parseInt(cmd.getOptionValue(SEGMENT_COUNT, "0")); float loadFactor = Float.parseFloat(cmd.getOptionValue(LOAD_FACTOR, "0")); int keyLen = Integer.parseInt(cmd.getOptionValue(KEY_LEN, "0")); int chunkSize = Integer.parseInt(cmd.getOptionValue(CHUNK_SIZE, "-1")); int fixedKeySize = Integer.parseInt(cmd.getOptionValue(FIXED_KEY_SIZE, "-1")); int fixedValueSize = Integer.parseInt(cmd.getOptionValue(FIXED_VALUE_SIZE, "-1")); int maxEntrySize = Integer.parseInt(cmd.getOptionValue(MAX_ENTRY_SIZE, "-1")); boolean unlocked = Boolean.parseBoolean(cmd.getOptionValue(UNLOCKED, "false")); HashAlgorithm hashMode = HashAlgorithm.valueOf(cmd.getOptionValue(HASH_MODE, "MURMUR3")); boolean bucketHistogram = Boolean.parseBoolean(cmd.getOptionValue(BUCKET_HISTOGRAM, "false")); double readWriteRatio = Double.parseDouble(cmd.getOptionValue(READ_WRITE_RATIO, ".5")); Driver[] drivers = new Driver[threads]; Random rnd = new Random(); String readKeyDistStr = cmd.getOptionValue(READ_KEY_DIST, DEFAULT_KEY_DIST); String writeKeyDistStr = cmd.getOptionValue(WRITE_KEY_DIST, DEFAULT_KEY_DIST); String valueSizeDistStr = cmd.getOptionValue(VALUE_SIZE_DIST, DEFAULT_VALUE_SIZE_DIST); DistributionFactory readKeyDist = OptionDistribution.get(readKeyDistStr); DistributionFactory writeKeyDist = OptionDistribution.get(writeKeyDistStr); DistributionFactory valueSizeDist = OptionDistribution.get(valueSizeDistStr); for (int i = 0; i < threads; i++) { drivers[i] = new Driver(readKeyDist.get(), writeKeyDist.get(), valueSizeDist.get(), readWriteRatio, rnd.nextLong()); } printMessage("Initializing OHC cache..."); OHCacheBuilder<Long, byte[]> builder = OHCacheBuilder.<Long, byte[]>newBuilder() .keySerializer( keyLen <= 0 ? BenchmarkUtils.longSerializer : new BenchmarkUtils.KeySerializer(keyLen)) .valueSerializer(BenchmarkUtils.serializer).capacity(capacity); if (cmd.hasOption(LOAD_FACTOR)) builder.loadFactor(loadFactor); if (cmd.hasOption(SEGMENT_COUNT)) builder.segmentCount(segmentCount); if (cmd.hasOption(HASH_TABLE_SIZE)) builder.hashTableSize(hashTableSize); if (cmd.hasOption(CHUNK_SIZE)) builder.chunkSize(chunkSize); if (cmd.hasOption(MAX_ENTRY_SIZE)) builder.maxEntrySize(maxEntrySize); if (cmd.hasOption(UNLOCKED)) builder.unlocked(unlocked); if (cmd.hasOption(HASH_MODE)) builder.hashMode(hashMode); if (cmd.hasOption(FIXED_KEY_SIZE)) builder.fixedEntrySize(fixedKeySize, fixedValueSize); Shared.cache = builder.build(); printMessage("Cache configuration: instance : %s%n" + " hash-table-size: %d%n" + " load-factor : %.3f%n" + " segments : %d%n" + " capacity : %d%n", Shared.cache, Shared.cache.hashTableSizes()[0], Shared.cache.loadFactor(), Shared.cache.segments(), Shared.cache.capacity()); String csvFileName = cmd.getOptionValue(CSV, null); PrintStream csv = null; if (csvFileName != null) { File csvFile = new File(csvFileName); csv = new PrintStream(new FileOutputStream(csvFile)); csv.println("# OHC benchmark - http://github.com/snazy/ohc"); csv.println("# "); csv.printf("# started on %s (%s)%n", InetAddress.getLocalHost().getHostName(), InetAddress.getLocalHost().getHostAddress()); csv.println("# "); csv.printf("# Warum-up/sleep seconds: %d / %d%n", warmUpSecs, coldSleepSecs); csv.printf("# Duration: %d seconds%n", duration); csv.printf("# Threads: %d%n", threads); csv.printf("# Capacity: %d bytes%n", capacity); csv.printf("# Read/Write Ratio: %f%n", readWriteRatio); csv.printf("# Segment Count: %d%n", segmentCount); csv.printf("# Hash table size: %d%n", hashTableSize); csv.printf("# Load Factor: %f%n", loadFactor); csv.printf("# Additional key len: %d%n", keyLen); csv.printf("# Read key distribution: '%s'%n", readKeyDistStr); csv.printf("# Write key distribution: '%s'%n", writeKeyDistStr); csv.printf("# Value size distribution: '%s'%n", valueSizeDistStr); csv.printf("# Type: %s%n", Shared.cache.getClass().getName()); csv.println("# "); csv.printf("# started at %s%n", new Date()); Properties props = System.getProperties(); csv.printf("# java.version: %s%n", props.get("java.version")); for (Map.Entry<Object, Object> e : props.entrySet()) { String k = (String) e.getKey(); if (k.startsWith("org.caffinitas.ohc.")) csv.printf("# %s: %s%n", k, e.getValue()); } csv.printf("# number of cores: %d%n", Runtime.getRuntime().availableProcessors()); csv.println("# "); csv.println("\"runtime\";" + "\"r_count\";" + "\"r_oneMinuteRate\";\"r_fiveMinuteRate\";\"r_fifteenMinuteRate\";\"r_meanRate\";" + "\"r_snapMin\";\"r_snapMax\";\"r_snapMean\";\"r_snapStdDev\";" + "\"r_snap75\";\"r_snap95\";\"r_snap98\";\"r_snap99\";\"r_snap999\";\"r_snapMedian\";" + "\"w_count\";" + "\"w_oneMinuteRate\";\"w_fiveMinuteRate\";\"w_fifteenMinuteRate\";\"w_meanRate\";" + "\"w_snapMin\";\"w_snapMax\";\"w_snapMean\";\"w_snapStdDev\";" + "\"w_snap75\";\"w_snap95\";\"w_snap98\";\"w_snap99\";\"w_snap999\";\"w_snapMedian\""); } printMessage( "Starting benchmark with%n" + " threads : %d%n" + " warm-up-secs: %d%n" + " idle-secs : %d%n" + " runtime-secs: %d%n", threads, warmUpSecs, coldSleepSecs, duration); ThreadPoolExecutor main = new ThreadPoolExecutor(threads, threads, coldSleepSecs + 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { volatile int threadNo; public Thread newThread(Runnable r) { return new Thread(r, "driver-main-" + threadNo++); } }); main.prestartAllCoreThreads(); // warm up if (warmUpSecs > 0) { printMessage("Start warm-up..."); runFor(warmUpSecs, main, drivers, bucketHistogram, csv); printMessage(""); logMemoryUse(); if (csv != null) csv.println("# warm up complete"); } // cold sleep if (coldSleepSecs > 0) { printMessage("Warm up complete, sleep for %d seconds...", coldSleepSecs); Thread.sleep(coldSleepSecs * 1000L); } // benchmark printMessage("Start benchmark..."); runFor(duration, main, drivers, bucketHistogram, csv); printMessage(""); logMemoryUse(); if (csv != null) csv.println("# benchmark complete"); // finish if (csv != null) csv.close(); System.exit(0); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
From source file:com.cloudhopper.commons.io.demo.FileServerMain.java
public static void loadFilesFromDir(String dir, int threads) { ThreadPoolExecutor ex = new ThreadPoolExecutor(threads, threads, 5000l, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); ex.prestartAllCoreThreads(); IdGenerator idGen = new UUIDIdGenerator(); final FileStore store = new SimpleNIOFileStore(idGen, "/tmp/fileStore/"); final long start = System.currentTimeMillis(); int count = 0; Iterator<File> it = FileUtils.iterateFiles(new File(dir), null, true); while (it.hasNext()) { final File f = it.next(); final int num = count++; Runnable job = new Runnable() { @Override//from ww w .j av a 2 s . co m public void run() { try { RandomAccessFile randomAccessFile = new RandomAccessFile(f, "r"); FileChannel fileChannel = randomAccessFile.getChannel(); Id id = store.write(fileChannel); System.out.println("(" + num + ") Stored " + f.getPath() + " as " + id.getName() + " after " + (System.currentTimeMillis() - start) + "ms"); } catch (Exception e) { logger.error("", e); } } }; ex.execute(job); } }
From source file:android.concurrent.ThreadPool.java
private static ThreadPoolExecutor createThreadPoolExecutor(String poolName) { ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(DEFAULT_BLOCKING_QUEUE_SIZE); // CallerRunsPolicy policy = new CallerRunsPolicy(); ThreadPoolExecutor.DiscardPolicy policy = new ThreadPoolExecutor.DiscardPolicy(); ThreadPoolExecutor excuter = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, UNIT, queue, new PoolThreadFactory(poolName), policy); excuter.prestartAllCoreThreads(); excuter.allowCoreThreadTimeOut(true); return excuter; }
From source file:com.l2jfree.util.concurrent.L2ThreadPool.java
public static void initThreadPools(ThreadPoolInitializer initializer) throws Exception { if (!ArrayUtils.isEmpty(_scheduledPools) || !ArrayUtils.isEmpty(_instantPools) || !ArrayUtils.isEmpty(_longRunningPools)) throw new Exception("The thread pool has been already set!"); initializer.initThreadPool();/*from w w w . j av a 2 s .c o m*/ _scheduledPools = initializer.getScheduledPools(); _instantPools = initializer.getInstantPools(); _longRunningPools = initializer.getLongRunningPools(); if (ArrayUtils.isEmpty(_scheduledPools)) { _log.info("No scheduled thread pool has been manually initialized, so initializing default one."); _scheduledPools = new ScheduledThreadPoolExecutor[] { new ScheduledThreadPoolExecutor( // // int corePoolSize 4) }; } if (ArrayUtils.isEmpty(_instantPools)) { _log.info("No instant thread pool has been manually initialized, so initializing default one."); _instantPools = new ThreadPoolExecutor[] { new ThreadPoolExecutor( // // int corePoolSize 0, // int maximumPoolSize Integer.MAX_VALUE, // long keepAliveTime 60L, // TimeUnit unit TimeUnit.SECONDS, // BlockingQueue<Runnable> workQueue new SynchronousQueue<Runnable>()) }; } if (ArrayUtils.isEmpty(_longRunningPools)) { _log.info("No long running thread pool has been manually initialized, so initializing default one."); _longRunningPools = new ThreadPoolExecutor[] { new ThreadPoolExecutor( // // int corePoolSize 0, // int maximumPoolSize Integer.MAX_VALUE, // long keepAliveTime 60L, // TimeUnit unit TimeUnit.SECONDS, // BlockingQueue<Runnable> workQueue new SynchronousQueue<Runnable>()) }; } for (ThreadPoolExecutor threadPool : getThreadPools()) { threadPool.setRejectedExecutionHandler(new L2RejectedExecutionHandler()); threadPool.prestartAllCoreThreads(); } scheduleAtFixedRate(new Runnable() { @Override public void run() { purge(); } }, 60000, 60000); _log.info("L2ThreadPool: Initialized with"); _log.info("\t... " + getPoolSize(_scheduledPools) + "/" + getMaximumPoolSize(_scheduledPools) + " scheduler,"); _log.info("\t... " + getPoolSize(_instantPools) + "/" + getMaximumPoolSize(_instantPools) + " instant,"); _log.info("\t... " + getPoolSize(_longRunningPools) + "/" + getMaximumPoolSize(_longRunningPools) + " long running thread(s)."); }
From source file:de.th.wildau.dsc.sne.webserver.WebServer.java
/** * Web server / main constructor./* w ww .j av a 2s. co m*/ * * @param startArguments */ public WebServer(String[] startArguments) { loadConfiguration(startArguments); Log.debug(Configuration.getInstance().toString()); Log.debug("Information about the OS: " + System.getProperty("os.name") + " - " + System.getProperty("os.version") + " - " + System.getProperty("os.arch")); if (Configuration.getConfig().getProxyHost() != null) { Log.debug("setup proxy configuration"); System.setProperty("http.proxyHost", Configuration.getConfig().getProxyHost()); System.setProperty("http.proxyPort", String.valueOf(Configuration.getConfig().getProxyPort())); } Log.debug("find supported scripting languages"); supportedScriptLanguages = Collections.unmodifiableList(ScriptExecutor.getSupportedScriptLanguages()); Log.debug("Supported Script Languages " + Arrays.toString(supportedScriptLanguages.toArray())); Log.info("instantiating web server"); try { ServerSocket server = new ServerSocket(Configuration.getConfig().getServerPort()); Log.debug("bound port " + Configuration.getConfig().getServerPort()); int corePoolSize = Runtime.getRuntime().availableProcessors(); int maxPoolSize = (2 * corePoolSize) + 1; Log.debug("core/max pool size: " + corePoolSize + "/" + maxPoolSize); LinkedBlockingQueue<Runnable> workerQueue = new LinkedBlockingQueue<Runnable>(); long keepAliveTime = 30; /* * keepAliveTime - If the pool currently has more than corePoolSize * threads, excess threads will be terminated if they have been idle * for more than the keepAliveTime. */ ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, workerQueue); threadPool.prestartAllCoreThreads(); Socket socket = null; while (true) { try { socket = server.accept(); Log.info(socket.getInetAddress().getHostName() + " client request"); threadPool.execute(new HttpHandler(socket)); Log.debug("current threads: " + threadPool.getActiveCount()); } catch (final IOException ex) { Log.error("Connection failed!", ex); } catch (final RejectedExecutionException ex) { // XXX [sne] RejectedExecutionException // http://stackoverflow.com/questions/1519725/why-does-executors-newcachedthreadpool-throw-java-util-concurrent-rejectedexecut // http://www.javamex.com/tutorials/threads/thread_pools_queues.shtml // http://stackoverflow.com/questions/2001086/how-to-make-threadpoolexecutors-submit-method-block-if-it-is-saturated Log.error("RejectedExecutionException", ex); socket.close(); } catch (final Exception ex) { Log.fatal("Unknown error!", ex); } } } catch (final IOException ex) { Log.fatal("Can not start the server!", ex); System.err.println("Can not start the server! " + ex.getMessage()); } catch (final Exception ex) { Log.fatal("Unknown error!", ex); } }
From source file:org.esigate.test.cases.PerformanceTestCase.java
/** * Execute la tache avec plusieurs Threads * //from ww w.j a v a2 s.com * @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: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 w w .jav a2 s . c o 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); }
From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java
@Test public void maxUsage_MultiThreaded() throws Exception { NamingThreadFactory factory = new NamingThreadFactory(); ThreadPoolExecutor e = new ThreadPoolExecutor(10, 10, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(), factory);// ww w . j av a 2 s .c o 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 Multithreaded 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 Multithreaded overall usage: " + actualUsage); }