Example usage for java.util.concurrent ExecutorService shutdown

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

Introduction

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

Prototype

void shutdown();

Source Link

Document

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

Usage

From source file:mase.conillon.ConillonMasterProblem.java

public static void runWithTimeout(Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception {
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final Future future = executor.submit(runnable);
    executor.shutdown(); // This does not cancel the already-scheduled task.
    try {//  w ww  .ja v  a  2 s .c  o m
        future.get(timeout, timeUnit);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        future.cancel(true);
        throw e;
    }
}

From source file:mase.conillon.ConillonMasterProblem.java

public static <T> T runWithTimeout(Callable<T> callable, long timeout, TimeUnit timeUnit) throws Exception {
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final Future<T> future = executor.submit(callable);
    executor.shutdown(); // This does not cancel the already-scheduled task.
    try {/*from ww w.  jav  a2 s  . c  o  m*/
        return future.get(timeout, timeUnit);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        future.cancel(true);
        throw e;
    }
}

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;
        }/*  ww  w . j a v  a  2s  . com*/

        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:gr.demokritos.iit.cru.creativity.reasoning.semantic.WebMiner.java

public static String WebMiner(String seed, int difficulty, String language, boolean compactForm)
        throws ClassNotFoundException, SQLException, IOException, InstantiationException,
        IllegalAccessException {/*from   w  ww  .ja v  a  2  s .c o m*/
    Gson gson = new Gson();
    Connect c = new Connect(language);
    RandomWordGenerator r = new RandomWordGenerator(c);
    String randomPhrase = r.selectRandomWord(seed, difficulty).replace(",", " ");
    InfoSummarization inf = new InfoSummarization(c);
    LinkedHashMap<String, Double> TagCloud = new LinkedHashMap<String, Double>();

    Set<String> pages = new HashSet<String>();
    ArrayList<String> urls = new ArrayList<String>();
    ArrayList<String> urls_temp = new ArrayList<String>();
    if (language.equalsIgnoreCase("en")) {
        if (randomPhrase.length() == 0) {
            randomPhrase = seed;
        }
        String bingAppId = c.getBingAppId();
        BingCrawler bc = new BingCrawler(bingAppId, language);
        urls_temp = bc.crawl(randomPhrase);
        int url_loop = 0;
        while ((url_loop < 5) && (url_loop < urls_temp.size())) {
            urls.add(urls_temp.get(url_loop));
            url_loop++;
        }
    } else if (language.equalsIgnoreCase("el")) {
        String bingAppId = c.getBingAppId();
        BingCrawler bc = new BingCrawler(bingAppId, language);
        urls_temp = bc.crawl(randomPhrase);
        int url_loop = 0;
        while ((url_loop < 5) && (url_loop < urls_temp.size())) {
            urls.add(urls_temp.get(url_loop));
            url_loop++;
        }
    } else if (language.equalsIgnoreCase("de")) {//keep only the first word of the random phrase for search
        if (randomPhrase.length() == 0) {
            randomPhrase = seed;
        }
        urls_temp = HTMLUtilities.linkExtractor(
                "http://www.fragfinn.de/kinderliste/suche?start=0&query=" + randomPhrase.split(" ")[0], "UTF-8",
                0);

        for (String url : urls_temp) {
            urls.add(StringEscapeUtils.unescapeHtml4(url));
            if (urls.size() == 5) {
                break;
            }
        }
    }
    String delims = "[{} .,;?!():\"]+";

    String[] words = randomPhrase.split(",");
    String[] user_keywords = seed.split(delims);
    if (urls.size() > 0) {
        ExecutorService threadPool = Executors.newFixedThreadPool(urls.size());
        for (String url : urls) {
            threadPool.submit(new HTMLPages(url, pages, language)); //stopWordSet, tokensHashMap,language));
            // threadPool.submit(HTMLTokenizer());
        }
        threadPool.shutdown();
        while (!threadPool.isTerminated()) {

        }

        LinkedHashMap<ArrayList<String>, Double> temp = inf.TopTermsBing(pages, compactForm);
        HashMap<String, Double> temp2 = new HashMap<String, Double>();
        for (ArrayList<String> stems : temp.keySet()) {
            for (int j = 0; j < stems.size(); j++) {
                String s = stems.get(j).split("\\{")[0];
                s = s.replace(",", " ");
                s = s.trim();

                boolean wordnet = true;
                //if term is not one of the initial random phrase
                for (int i = 0; i < words.length; i++) {
                    if (s.equalsIgnoreCase(words[i])) {
                        wordnet = false;
                    }
                }
                //and if it 's not in the initial words of user
                for (int i = 0; i < user_keywords.length; i++) {
                    if (s.equalsIgnoreCase(user_keywords[i])) {
                        wordnet = false;
                    }
                }
                //in german or greek, ignore english words from search english words
                if (language.equalsIgnoreCase("de") || language.equalsIgnoreCase("el")) {
                    if (c.getWn().getCommonPos(s) != null) {
                        continue;
                    }
                }
                //return it with its stem's weight
                if (wordnet) {
                    //for every stem, put each of its corresponding terms to tagCloud with the stem's tf
                    temp2.put(stems.get(j), temp.get(stems));
                }
            }
        }
        TagCloud = inf.sortHashMapByValues(temp2);
        threadPool.shutdownNow();
    }
    String json = gson.toJson(TagCloud);
    c.CloseConnection();
    return json;
}

From source file:de.javakaffee.sandbox.getfj.WordCountFJ.java

public static TreeMap<String, Integer> getWordsAndCountsFromFilesInParallel(final List<String> fileNames) {
    final ExecutorService pool = newFixedThreadPool(16);
    final ParModule m = parModule(Strategy.<Unit>executorStrategy(pool));

    // Long wordCount = countWords(fileNames.map(readFile), m).claim();
    final TreeMap<String, Integer> result = getWordsAndCountsFromFiles(fileNames, m).claim();

    pool.shutdown();

    return result;
}

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  av  a 2 s. c om

    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:org.zenoss.zep.impl.Application.java

private static void stopExecutor(ExecutorService executorService) {
    executorService.shutdown();
    try {//from   www .  j  a v  a 2 s  . c  o  m
        executorService.awaitTermination(0L, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        executorService.shutdownNow();
    }
}

From source file:de.javakaffee.sandbox.getfj.WordCountFJ.java

public static Long countWords(final List<String> fileNames) {

    final ExecutorService pool = newFixedThreadPool(1);
    final ParModule m = parModule(Strategy.<Unit>executorStrategy(pool));

    // Long wordCount = countWords(fileNames.map(readFile), m).claim();
    final Long wordCount = countWordsFromFiles(fileNames, m).claim();
    System.out.println("Word Count: " + wordCount);

    pool.shutdown();

    return wordCount;
}

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  w w  .java  2  s  .  co 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   www.ja va  2s.  c o  m*/

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