List of usage examples for java.util.concurrent ExecutorService shutdown
void shutdown();
From source file:at.ac.tuwien.dsg.cloud.utilities.gateway.registry.SpringConfig.java
@Bean public ExecutorService executorService() { ExecutorService bean = Executors.newCachedThreadPool(); regestryService.registerService(new Shutdownable() { @Override/*from w ww. j a v a 2s .co m*/ public void shutdown() { bean.shutdown(); } }); return bean; }
From source file:com.cloudera.oryx.ml.serving.als.LoadIT.java
@Test public void testRecommendLoad() throws Exception { // Since latency is more important, and local machine will also be busy handling requests, // use few concurrent workers, like 1: int workers = 1; AtomicLong count = new AtomicLong(); Mean meanReqTimeMS = new Mean(); long start = System.currentTimeMillis(); List<Callable<Void>> tasks = new ArrayList<>(workers); for (int i = 0; i < workers; i++) { tasks.add(new LoadCallable(Integer.toString(i), meanReqTimeMS, count, start)); }//from ww w. j ava 2s . c om ExecutorService executor = Executors.newFixedThreadPool(workers); try { executor.invokeAll(tasks); } finally { executor.shutdown(); } int totalRequests = workers * REQS_PER_WORKER; log(totalRequests, meanReqTimeMS, start); Assert.assertTrue(meanReqTimeMS.getResult() < 300.0); }
From source file:com.topekalabs.synchronization.LockTest.java
@Test public void testWithContention() { final int numThreads = 4; ExecutorService es = Executors.newFixedThreadPool(numThreads); //Warmup thread pool testWithContentionHelper(numThreads, es); testWithContentionHelper(numThreads, es); es.shutdown(); }
From source file:net.openhft.chronicle.logger.VanillChronicleQueuePerfTest.java
@Test public void testMultiThreadLogging() throws IOException, InterruptedException { final int RUNS = 15000000; final int THREADS = Runtime.getRuntime().availableProcessors(); for (int size : new int[] { 64, 128, 256 }) { {//from w w w.j av a 2s. c o m final long start = System.nanoTime(); ExecutorService es = Executors.newFixedThreadPool(THREADS); for (int t = 0; t < THREADS; t++) { es.submit(new RunnableLogger(RUNS, size)); } es.shutdown(); es.awaitTermination(2, TimeUnit.MINUTES); final long time = System.nanoTime() - start; System.out.printf( "ChronicleLog.MT (runs=%d, min size=%03d, elapsed=%.3f ms) took an average of %.3f us per entry\n", RUNS, size, time / 1e6, time / 1e3 / (RUNS * THREADS)); } } }
From source file:no.ntnu.idi.socialhitchhiking.map.GeoHelper.java
/** * Retrieves a {@link List} of addresses that match the given {@link GeoPoint}. * The first element in the list has the best match (but is not guaranteed to be correct). <br><br> * /*from ww w . j a va 2s.co m*/ * This method tries to use the {@link Geocoder} to transform a (latitude, longitude) * coordinate into addresses, and if this fails (witch it most likely will under emulation), it * tries to use a method from the {@link GeoHelper}-class. * * @param location The location that is transformed into a list of addresses * @param maxResults The maximum number of addresses to retrieve (should be small). * @param maxAddressLines The maximum number of lines in the addresses. This should be high if you want a complete address! If it is smaller than the total number of lines in the address, it cuts off the last part...) * @return Returns the {@link List} of addresses (as {@link String}s). */ public static List<String> getAddressesAtPoint(final GeoPoint location, final int maxResults, int maxAddressLines) { List<String> addressList = new ArrayList<String>(); List<Address> possibleAddresses = new ArrayList<Address>(); Address address = new Address(Locale.getDefault()); String addressString = "Could not find the address..."; ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<List<Address>> callable = new Callable<List<Address>>() { @Override public List<Address> call() throws IOException { return fancyGeocoder.getFromLocation(location.getLatitudeE6() / 1E6, location.getLongitudeE6() / 1E6, maxResults); } }; Future<List<Address>> future = executor.submit(callable); try { possibleAddresses = future.get(); } catch (InterruptedException e1) { possibleAddresses = GeoHelper.getAddressesFromLocation(location.getLatitudeE6() / 1E6, location.getLongitudeE6() / 1E6, maxResults); } catch (ExecutionException e1) { possibleAddresses = GeoHelper.getAddressesFromLocation(location.getLatitudeE6() / 1E6, location.getLongitudeE6() / 1E6, maxResults); } executor.shutdown(); if (possibleAddresses.size() > 0) { for (int i = 0; i < possibleAddresses.size(); i++) { addressString = ""; address = possibleAddresses.get(i); for (int j = 0; j <= address.getMaxAddressLineIndex() && j <= maxAddressLines; j++) { addressString += address.getAddressLine(j); addressString += "\n"; } addressList.add(addressString.trim()); } } return addressList; }
From source file:com.nts.alphamale.handler.ExecutorHandler.java
public void shutdownExecutor(ExecutorService executor, int awaitTermination) { if (null != executor && !executor.isShutdown()) { executor.shutdown(); try {// ww w .jav a 2 s.co m if (!executor.awaitTermination(awaitTermination, TimeUnit.SECONDS)) { executor.shutdownNow(); if (!executor.awaitTermination(awaitTermination, TimeUnit.SECONDS)) { log.error("Executor did not terminate"); } } } catch (InterruptedException e) { executor.shutdownNow(); } } }
From source file:de.huberlin.wbi.hiway.am.cuneiform.CuneiformApplicationMaster.java
public CuneiformApplicationMaster() { super();//from w ww. j a va 2s. c o m ExecutorService executor = Executors.newCachedThreadPool(); creActor = new HiWayCreActor(this); executor.submit(creActor); ticketSrc = new TicketSrcActor(creActor); executor.submit(ticketSrc); executor.shutdown(); }
From source file:com.polyvi.xface.extension.XExtensionManager.java
/** * /*from w w w.j a va 2 s. c o m*/ */ private void shutdownAndAwaitTermination(ExecutorService pool) { pool.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!pool.awaitTermination(THREAD_POOL_TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS)) { pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(THREAD_POOL_TERMINATION_TIMEOUT, TimeUnit.MILLISECONDS)) { XLog.d(CLASS_NAME, "Thread Pool did not terminate"); } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } }
From source file:com.joyent.manta.benchmark.Benchmark.java
/** * Method used to run a multi-threaded benchmark. * * @param method to measure// w ww . j a v a 2 s . c o m * @param path path to store benchmarking test data * @param iterations number of iterations to run * @param concurrency number of threads to run * @throws IOException thrown when we can't communicate with the server */ private static void multithreadedBenchmark(final String method, final String path, final int iterations, final int concurrency) throws IOException { final AtomicLong fullAggregation = new AtomicLong(0L); final AtomicLong serverAggregation = new AtomicLong(0L); final AtomicLong count = new AtomicLong(0L); final long perThreadCount = perThreadCount(iterations, concurrency); System.out.printf("Running %d iterations per thread\n", perThreadCount); final long testStart = System.nanoTime(); Runtime.getRuntime().addShutdownHook(new Thread(Benchmark::cleanUp)); final Callable<Void> worker = () -> { for (int i = 0; i < perThreadCount; i++) { Duration[] durations; if (method.equals("put")) { durations = measurePut(sizeInBytesOrNoOfDirs); } else if (method.equals("putDir")) { durations = measurePutDir(sizeInBytesOrNoOfDirs); } else { durations = measureGet(path); } long fullLatency = durations[0].toMillis(); long serverLatency = durations[1].toMillis(); fullAggregation.addAndGet(fullLatency); serverAggregation.addAndGet(serverLatency); System.out.printf("%s %d full=%dms, server=%dms, thread=%s\n", method, count.getAndIncrement(), fullLatency, serverLatency, Thread.currentThread().getName()); } return null; }; final Thread.UncaughtExceptionHandler handler = (t, e) -> LOG.error("Error when executing benchmark", e); final AtomicInteger threadCounter = new AtomicInteger(0); ThreadFactory threadFactory = r -> { Thread t = new Thread(r); t.setDaemon(true); t.setUncaughtExceptionHandler(handler); t.setName(String.format("benchmark-%d", threadCounter.incrementAndGet())); return t; }; ExecutorService executor = Executors.newFixedThreadPool(concurrency, threadFactory); List<Callable<Void>> workers = new ArrayList<>(concurrency); for (int i = 0; i < concurrency; i++) { workers.add(worker); } try { List<Future<Void>> futures = executor.invokeAll(workers); boolean completed = false; while (!completed) { try (Stream<Future<Void>> stream = futures.stream()) { completed = stream.allMatch((f) -> f.isDone() || f.isCancelled()); if (!completed) { Thread.sleep(CHECK_INTERVAL); } } } } catch (InterruptedException e) { return; } finally { System.err.println("Shutting down the thread pool"); executor.shutdown(); } final long testEnd = System.nanoTime(); final long fullAverage = Math.round(fullAggregation.get() / iterations); final long serverAverage = Math.round(serverAggregation.get() / iterations); final long totalTime = Duration.ofNanos(testEnd - testStart).toMillis(); System.out.printf("Average full latency: %d ms\n", fullAverage); System.out.printf("Average server latency: %d ms\n", serverAverage); System.out.printf("Total test time: %d ms\n", totalTime); System.out.printf("Total invocations: %d\n", count.get()); }
From source file:edu.cmu.cs.lti.ark.fn.identification.training.AlphabetCreationThreaded.java
/** * Splits frameElementLines into numThreads equally-sized batches and creates an alphabet * file for each one./*w ww.ja v a2 s. c om*/ * * @throws IOException */ public Multiset<String> createAlphabet() throws IOException, ExecutionException, InterruptedException { final List<String> frameLines = Files.readLines(new File(frameElementsFile), Charsets.UTF_8) .subList(startIndex, endIndex); final int batchSize = (int) Math.ceil(frameLines.size() / (double) numThreads); final List<List<String>> frameLinesPartition = Lists.partition(frameLines, batchSize); final List<String> parseLines = Files.readLines(new File(parseFile), Charsets.UTF_8); final Multiset<String> alphabet = ConcurrentHashMultiset.create(); final List<Callable<Integer>> jobs = Lists.newArrayListWithExpectedSize(numThreads); for (final int i : xrange(numThreads)) { jobs.add(newJob(i, frameLinesPartition.get(i), parseLines, alphabet)); } final ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); final List<Future<Integer>> results = threadPool.invokeAll(jobs); threadPool.shutdown(); try { for (Integer i : xrange(results.size())) { logger.info(String.format("Thread %d successfully processed %d lines", i, results.get(i).get())); } } finally { threadPool.shutdownNow(); } return alphabet; }