List of usage examples for java.util.concurrent ExecutorService submit
Future<?> submit(Runnable task);
From source file:com.google.zxing.client.android.result.supplement.SupplementalInfoRetriever.java
public static void maybeInvokeRetrieval(TextView textView, ParsedResult result, Handler handler, HistoryManager historyManager, Context context) { Collection<SupplementalInfoRetriever> retrievers = new ArrayList<SupplementalInfoRetriever>(1); if (result instanceof URIParsedResult) { retrievers.add(new URIResultInfoRetriever(textView, (URIParsedResult) result, handler, historyManager, context));/*w w w .ja v a 2s.c o m*/ } else if (result instanceof ProductParsedResult) { String productID = ((ProductParsedResult) result).getProductID(); retrievers.add(new ProductResultInfoRetriever(textView, productID, handler, historyManager, context)); } else if (result instanceof ISBNParsedResult) { String isbn = ((ISBNParsedResult) result).getISBN(); retrievers.add(new ProductResultInfoRetriever(textView, isbn, handler, historyManager, context)); retrievers.add(new BookResultInfoRetriever(textView, isbn, handler, historyManager, context)); } for (SupplementalInfoRetriever retriever : retrievers) { ExecutorService executor = getExecutorService(); Future<?> future = executor.submit(retriever); // Make sure it's interrupted after a short time though executor.submit(new KillerCallable(future, 10, TimeUnit.SECONDS)); } }
From source file:Main.java
public static long pmax(final long[][] arr, int numThreads) { ExecutorService pool = Executors.newFixedThreadPool(numThreads); try {// w w w. jav a 2s . c o m List<Future<Long>> list = new ArrayList<Future<Long>>(); for (int i = 0; i < arr.length; i++) { final long[] subArr = arr[i]; list.add(pool.submit(new Callable<Long>() { public Long call() { long max = Long.MIN_VALUE; for (int j = 0; j < subArr.length; j++) { if (subArr[j] > max) { max = subArr[j]; } } return max; } })); } // find the max of each slice's max: long max = Long.MIN_VALUE; for (Future<Long> future : list) { long threadMax = future.get(); System.out.println("threadMax: " + threadMax); if (threadMax > max) { max = threadMax; } } return max; } catch (Exception e) { System.out.println(e); return -1; } finally { pool.shutdown(); } }
From source file:com.jdom.ajatt.viewer.util.HtmlUtil.java
public static String getRequest(Activity activity, final String url) { SharedPreferences prefs = activity.getSharedPreferences(CLASS_NAME, Context.MODE_PRIVATE); String cachedUrlContents = prefs.getString(url, null); String urlRetrievalTimeKey = url + ".time"; long cachedUrlRetrievalTime = prefs.getLong(urlRetrievalTimeKey, 0L); long ageOfCachedData = System.currentTimeMillis() - cachedUrlRetrievalTime; if (cachedUrlRetrievalTime == 0) { Log.d(CLASS_NAME, "Did not find cached data for URL [" + url + "]."); } else {/* ww w. j a v a 2 s. c o m*/ Log.d(CLASS_NAME, "URL [" + url + "] has been cached for [" + ageOfCachedData + "] ms."); } Future<String> result = null; boolean expired = ageOfCachedData > CACHE_URL_MILLISECONDS; if (expired) { Log.d(CLASS_NAME, "URL [" + url + "] data is stale."); } else { long timeRemainingValidCache = CACHE_URL_MILLISECONDS - ageOfCachedData; Log.d(CLASS_NAME, "URL [" + url + "] data has [" + timeRemainingValidCache + "] ms of validity remaining."); } if (cachedUrlContents == null || expired) { Callable<String> callable = new Callable<String>() { public String call() throws Exception { long start = System.currentTimeMillis(); Log.d(CLASS_NAME, "Retrieving URL [" + url + "]."); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); try { HttpResponse response = client.execute(request); return HttpHelper.request(response); } catch (Exception ex) { Log.e(CLASS_NAME, "Failure to retrieve the url!", ex); return null; } finally { Log.d(CLASS_NAME, "Retrieving URL [" + url + "] took [" + (System.currentTimeMillis() - start) + "] ms to retrieve."); } } }; ExecutorService executor = Executors.newSingleThreadExecutor(); result = executor.submit(callable); } if (cachedUrlContents == null) { try { cachedUrlContents = result.get(); Editor editor = prefs.edit(); editor.putLong(urlRetrievalTimeKey, System.currentTimeMillis()); editor.putString(url, cachedUrlContents); editor.commit(); } catch (Exception e) { Log.e(CLASS_NAME, "Failure to retrieve the url!", e); } } return cachedUrlContents; }
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 {// w w w .j a 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:Main.java
public static void invokeAll(final List<Runnable> tasks, final ExecutorService executor) throws InterruptedException, ExecutionException { ExecutionException saved = null; if (executor != null) { final List<Future<?>> futures = new ArrayList<>(); for (final Runnable task : tasks) futures.add(executor.submit(task)); for (final Future<?> future : futures) { try { future.get();/*from www .j a v a 2 s . c o m*/ } catch (InterruptedException e) { throw e; } catch (ExecutionException e) { if (saved == null) { saved = e; } else { saved.addSuppressed(e); } } } } else { for (final Runnable task : tasks) { try { task.run(); } catch (Exception e) { if (saved == null) { saved = new ExecutionException(e); } else { saved.addSuppressed(e); } } } } if (saved != null) throw saved; }
From source file:com.netsteadfast.greenstep.util.SystemExpressionJobUtils.java
public static SysExprJobLogVO executeJobForManual(String expressionJobOid) throws ServiceException, Exception { ExpressionJobObj jobObj = getExpressionJobForManualMode(expressionJobOid); ExecutorService exprJobPool = Executors.newFixedThreadPool(1); jobObj = exprJobPool.submit(new ExpressionJobExecuteCallable(jobObj)).get(); exprJobPool.shutdown();//from w w w.j a v a 2s . c om return jobObj.getSysExprJobLog(); }
From source file:com.clxcommunications.xms.PagedFetcherTest.java
private static PagedFetcher<Integer> mockedFetcher(final List<List<Integer>> pages) { final ExecutorService executor = Executors.newSingleThreadExecutor(); return new PagedFetcher<Integer>() { @Override//w ww. j av a 2s . co m Future<Page<Integer>> fetchAsync(final int page, FutureCallback<Page<Integer>> callback) { return executor.submit(mockedFetchCallable(pages, page)); } }; }
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 ava 2s . 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.uniteddev.Unity.Downloader.java
public static void renameFiles() throws IOException, InterruptedException { Login.progressText.setText("Renaming files..."); System.out.println("Renaming files..."); class renameFile implements Runnable { private int i; renameFile(int i) { this.i = i; }//www .j a v a 2s . c o m public void run() { //System.out.println("Currently attempting Pool Index: "+this.i); String file = rename_files.get(this.i); if (file.contains("%20") || file.contains("%5b") || file.contains("%5d")) { file = namefix(file); File oldfile = new File(Minecraft.getWorkingDirectory(), rename_files.get(this.i)); if (oldfile.exists()) { File newfile = new File(Minecraft.getWorkingDirectory(), file); oldfile.renameTo(newfile); System.out.println("Renamed " + oldfile.getName() + " to " + newfile.getName()); } } } } ExecutorService pool = Executors.newFixedThreadPool(cores + 4); for (int i = 0; i < rename_files.size(); i++) { pool.submit(new renameFile(i)); } pool.shutdown(); pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); }
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 2 s. c o 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); }