Example usage for java.util.concurrent ExecutorService awaitTermination

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

Introduction

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

Prototype

boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;

Source Link

Document

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Usage

From source file:org.apache.stratos.common.threading.StratosThreadPool.java

public static void shutdown(String identifier) {

    ExecutorService executorService = executorServiceMap.get(identifier);
    if (executorService == null) {
        log.warn("No executor service found for id " + identifier + ", unable to shut down");
        return;/*from   ww w . jav  a 2  s . com*/
    }

    // try to shut down gracefully
    executorService.shutdown();
    // wait 10 secs till terminated
    try {
        if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
            log.info("Thread Pool [id] " + identifier + " did not finish all tasks before "
                    + "timeout, forcefully shutting down");
            executorService.shutdownNow();
        }
    } catch (InterruptedException e) {
        // interrupted, shutdown now
        executorService.shutdownNow();
    }

    // remove from the map
    executorServiceMap.remove(identifier);

    log.info("Successfully shutdown thread pool associated with id: " + identifier);
}

From source file:com.uniteddev.Unity.Downloader.java

public static void removeOutdated() throws IOException, InterruptedException {
    Login.progressText.setText("Removing outdated files...");
    System.out.println("Removing outdated files...");
    class removefile implements Runnable {
        private int i;

        removefile(int i) {
            this.i = i;
        }//w  ww . j a va  2s .  co  m

        public void run() {
            if (!((folders.get(this.i).contains("bin/")) || (folders.get(this.i).contains("resources/")))) {
                try {
                    //System.out.println("Currently attempting Pool Index: "+this.i);
                    ArrayList<String> online_list = getDirectoryListing(folders.get(this.i));
                    ArrayList<String> offline_list = new ArrayList<String>();
                    if (new File(Minecraft.getWorkingDirectory(), folders.get(this.i)).isDirectory()) {
                        File[] offline_files = new File(Minecraft.getWorkingDirectory(), folders.get(this.i))
                                .listFiles();
                        for (int j = 0; j < offline_files.length; j++) {
                            if (!offline_files[j].isDirectory()) {
                                offline_list.add(offline_files[j].getName());
                            }
                        }
                    }
                    for (int j = 0; j < online_list.size(); j++) {
                        online_list.set(j, namefix(online_list.get(j)));
                    }
                    for (int j = 0; j < offline_list.size(); j++) {
                        if (!online_list.contains(offline_list.get(j))) {
                            clean(Minecraft.getWorkingDirectory() + File.separator + folders.get(this.i),
                                    offline_list.get(j));
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    ExecutorService pool = Executors.newFixedThreadPool(cores + 2);
    for (int i = 0; i < folders.size(); i++) {
        pool.submit(new removefile(i));
    }
    pool.shutdown();
    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}

From source file:com.aol.advertising.qiao.util.CommonUtils.java

public static void shutdownAndAwaitTermination(ExecutorService pool, int waitTime, TimeUnit timeUnit) {
    pool.shutdown(); // Disable new tasks from being submitted
    try {/*from ww w.  j  a v a2 s.  c  o m*/
        // Wait a while for existing tasks to terminate
        if (!pool.awaitTermination(waitTime, timeUnit)) {
            pool.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!pool.awaitTermination(waitTime, timeUnit))
                logger.warn("Executor did not terminate");
        }
    } catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        pool.shutdownNow();
    }
}

From source file:com.app.util.SearchResultUtil.java

public static void performSearch() throws DatabaseConnectionException, SQLException {

    long startTime = System.nanoTime();

    ExecutorService executor = Executors.newFixedThreadPool(_THREAD_POOL_SIZE);

    List<Integer> userIds = UserUtil.getUserIds(true);

    for (int userId : userIds) {
        SearchResultRunnable searchResultRunnable = new SearchResultRunnable(userId);

        executor.execute(searchResultRunnable);
    }/*from ww w .  j  a va  2 s  .c o  m*/

    executor.shutdown();

    try {
        executor.awaitTermination(_THREAD_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException ie) {
        _log.error("The executor encountered an exception", ie);
    }

    long endTime = System.nanoTime();

    _log.info("Performing searches for {} users took {} milliseconds", userIds.size(),
            (endTime - startTime) / 1000000);
}

From source file:com.uniteddev.Unity.Downloader.java

public static void downloadFiles() throws MalformedURLException, IOException, InterruptedException {

    class downloadFile implements Runnable {
        private int i;

        downloadFile(int i) {
            this.i = i;
        }// w ww .  j  a  v a2 s . c  o m

        public void run() {
            String filename = files.get(this.i).substring(files.get(this.i).lastIndexOf('/') + 1,
                    files.get(this.i).length());
            File f = new File(Minecraft.getWorkingDirectory(), files.get(this.i));
            try {
                Login.progressText.setText("Downloading: " + filename);
                System.out.println("Downloading: " + filename);
                //System.out.println("Currently attempting Pool Index: "+this.i);
                HttpURLConnection connect_url = setupHTTP(Unity.url + Unity.folder + "/" + files.get(this.i));
                FileUtils.copyInputStreamToFile(connect_url.getInputStream(), f);
            } catch (FileNotFoundException e) {
                Login.progressText.setText("File not found!");
            } catch (MalformedURLException e) {
                System.out.println("DEV: FIX URL");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("FileSystem Error");
                e.printStackTrace();
            }
        }
    }

    Login.progressText.setText("Downloading new files...");
    System.out.println("Downloading new files...");
    System.out.println("Number of files to download: " + files.size());
    ExecutorService pool = Executors.newFixedThreadPool(10);
    for (int i = 0; i < files.size(); i++) {
        pool.submit(new downloadFile(i));
        Login.progress.setValue((int) (((double) i / files.size()) * 100));
    }
    pool.shutdown();
    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}

From source file:com.ning.metrics.collector.TestPerformance.java

private static long scheduleScribeAgents() throws InterruptedException {
    ExecutorService e = Executors.newFixedThreadPool(THREADPOOL_SIZE,
            new NamedThreadFactory("Performance tests (Scribe client)"));

    long startTime = System.currentTimeMillis();
    for (int i = 0; i < NUMBER_OF_SCRIBE_CLIENTS; i++) {
        e.execute(new ScribeClient());
        log.debug(String.format("Thread %d/%d submitted", i + 1, NUMBER_OF_SCRIBE_CLIENTS));
    }/*from ww  w.  j a va2 s . c  o  m*/

    e.shutdown();
    e.awaitTermination(10, TimeUnit.MINUTES);
    return startTime;
}

From source file:net.ymate.platform.module.search.Searchs.java

public static void __doStopSafed(ExecutorService pool) {
    if (pool != null) {
        pool.shutdown();/*from w w w . ja v  a  2s .  c o m*/
        try {
            if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
                pool.shutdownNow();
            }
        } catch (InterruptedException ex) {
            // Nothing..
            ex.printStackTrace();
        }
    }
}

From source file:org.zenoss.zep.impl.Application.java

private static void stopExecutor(ExecutorService executorService) {
    executorService.shutdown();// w w w. j a v a2s  . c om
    try {
        executorService.awaitTermination(0L, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        executorService.shutdownNow();
    }
}

From source file:com.amazon.janusgraph.example.MarvelGraphFactory.java

public static void load(final JanusGraph graph, final int rowsToLoad, final boolean report) throws Exception {

    JanusGraphManagement mgmt = graph.openManagement();
    if (mgmt.getGraphIndex(CHARACTER) == null) {
        final PropertyKey characterKey = mgmt.makePropertyKey(CHARACTER).dataType(String.class).make();
        mgmt.buildIndex(CHARACTER, Vertex.class).addKey(characterKey).unique().buildCompositeIndex();
    }/*from www  .ja  va  2s. c o  m*/
    if (mgmt.getGraphIndex(COMIC_BOOK) == null) {
        final PropertyKey comicBookKey = mgmt.makePropertyKey(COMIC_BOOK).dataType(String.class).make();
        mgmt.buildIndex(COMIC_BOOK, Vertex.class).addKey(comicBookKey).unique().buildCompositeIndex();
        mgmt.makePropertyKey(WEAPON).dataType(String.class).make();
        mgmt.makeEdgeLabel(APPEARED).multiplicity(Multiplicity.MULTI).make();
    }
    mgmt.commit();

    ClassLoader classLoader = MarvelGraphFactory.class.getClassLoader();
    URL resource = classLoader.getResource("META-INF/marvel.csv");
    int line = 0;
    Map<String, Set<String>> comicToCharacter = new HashMap<>();
    Map<String, Set<String>> characterToComic = new HashMap<>();
    Set<String> characters = new HashSet<>();
    BlockingQueue<Runnable> creationQueue = new LinkedBlockingQueue<>();
    try (CSVReader reader = new CSVReader(new InputStreamReader(resource.openStream()))) {
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null && line < rowsToLoad) {
            line++;
            String comicBook = nextLine[1];
            String[] characterNames = nextLine[0].split("/");
            if (!comicToCharacter.containsKey(comicBook)) {
                comicToCharacter.put(comicBook, new HashSet<String>());
            }
            List<String> comicCharacters = Arrays.asList(characterNames);
            comicToCharacter.get(comicBook).addAll(comicCharacters);
            characters.addAll(comicCharacters);

        }
    }

    for (String character : characters) {
        creationQueue.add(new CharacterCreationCommand(character, graph));
    }

    BlockingQueue<Runnable> appearedQueue = new LinkedBlockingQueue<>();
    for (String comicBook : comicToCharacter.keySet()) {
        creationQueue.add(new ComicBookCreationCommand(comicBook, graph));
        Set<String> comicCharacters = comicToCharacter.get(comicBook);
        for (String character : comicCharacters) {
            AppearedCommand lineCommand = new AppearedCommand(graph, new Appeared(character, comicBook));
            appearedQueue.add(lineCommand);
            if (!characterToComic.containsKey(character)) {
                characterToComic.put(character, new HashSet<String>());
            }
            characterToComic.get(character).add(comicBook);
        }
        REGISTRY.histogram("histogram.comic-to-character").update(comicCharacters.size());
    }

    int maxAppearances = 0;
    String maxCharacter = "";
    for (String character : characterToComic.keySet()) {
        Set<String> comicBookSet = characterToComic.get(character);
        int numberOfAppearances = comicBookSet.size();
        REGISTRY.histogram("histogram.character-to-comic").update(numberOfAppearances);
        if (numberOfAppearances > maxAppearances) {
            maxCharacter = character;
            maxAppearances = numberOfAppearances;
        }
    }
    LOG.info("Character {} has most appearances at {}", maxCharacter, maxAppearances);

    ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
    for (int i = 0; i < POOL_SIZE; i++) {
        executor.execute(new BatchCommand(graph, creationQueue));
    }
    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + creationQueue.size());
        if (report) {
            REPORTER.report();
        }
    }

    executor = Executors.newSingleThreadExecutor();
    executor.execute(new BatchCommand(graph, appearedQueue));

    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + appearedQueue.size());
        if (report) {
            REPORTER.report();
        }
    }
    LOG.info("MarvelGraphFactory.load complete");
}

From source file:example.rhino.DynamicScopesWithHandlebars.java

private static void runScripts(Context cx, Script script, ExecutorService executor) {
    ScriptableObject sharedScope = cx.initStandardObjects(null, true);
    script.exec(cx, sharedScope);/*from w ww.j  ava  2 s.c o  m*/

    Runnable[] run = new Runnable[NUM_THREAD];
    for (int i = 0; i < NUM_THREAD; i++) {

        String source2 = "Handlebars.precompile(template)";

        run[i] = new PerThread(sharedScope, source2, i);
    }
    for (int i = 0; i < NUM_THREAD; i++) {
        executor.execute(run[i]);
    }

    executor.shutdown();

    try {
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}