List of usage examples for java.util.concurrent ExecutorService submit
Future<?> submit(Runnable task);
From source file:com.emc.vipr.sync.CasMigrationTest.java
protected void delete(FPPool pool, List<String> clipIds) throws Exception { ExecutorService service = Executors.newFixedThreadPool(CAS_SETUP_THREADS); System.out.print("Deleting clips"); for (String clipId : clipIds) { service.submit(new ClipDeleter(pool, clipId)); }//w w w .j av a2s . c o m service.shutdown(); service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES); service.shutdownNow(); System.out.println(); }
From source file:hulo.localization.models.obs.GaussianProcess.java
public double[] logProbaygivenXMultiThread(final double[][] X, final double[] y) { ExecutorService ex = ExecutorServiceHolder.getExecutorService(); int n = X.length; final double logpro[] = new double[n]; Future<?>[] futures = new Future<?>[n]; for (int i = 0; i < n; i++) { final int idx = i; futures[i] = ex.submit(new Runnable() { public void run() { logpro[idx] = logProbaygivenx(X[idx], y); }//www. j a v a 2s . c o m }); } for (int i = 0; i < n; i++) { try { futures[i].get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } return logpro; }
From source file:org.codice.pubsub.stomp.SubscriptionQueryMessageListener.java
private boolean createSubscription(SearchQueryMessage queryMsg) { boolean success = false; String subscriptionId = queryMsg.getSubscriptionId(); //Build Query String cqlText = queryMsg.getQueryString(); if (StringUtils.isNotEmpty(cqlText)) { Filter filter = null;//from w w w .j a v a 2s .c o m try { filter = CQL.toFilter(cqlText); } catch (CQLException e) { LOGGER.error("Fatal error while trying to build CQL-based Filter from cqlText : " + cqlText); return success; } //Add CSW Record Mapper Filter Visitor for more CQL filtering options try { FilterVisitor f = new CswRecordMapperFilterVisitor(); filter = (Filter) filter.accept(f, null); } catch (UnsupportedOperationException ose) { try { throw new CswException(ose.getMessage(), CswConstants.INVALID_PARAMETER_VALUE, null); } catch (CswException e) { LOGGER.error(e.getMessage()); return success; } } if (catalogFramework != null && filter != null) { LOGGER.trace("Catalog Frameowork: " + catalogFramework.getVersion()); //Set creation and last modified date times Calendar now = Calendar.getInstance(); queryMsg.setCreationDate(now.getTimeInMillis()); queryMsg.setLastModifiedDate(now.getTimeInMillis()); //Starts this class in a thread ExecutorService executor = Executors.newFixedThreadPool(NUM_QUERY_SEND_THREADS); QueryAndSend qasInst = queryAndSend.newInstance(); qasInst.setEnterprise(DEFAULT_IS_ENTERPRISE); qasInst.setFilter(filter); qasInst.setSubscriptionId(subscriptionId); Callable worker = qasInst; executor.submit(worker); //Add to Subscription Map ObjectMapper mapper = new ObjectMapper(); String jsonMsg = null; try { jsonMsg = mapper.writeValueAsString(queryMsg); } catch (JsonProcessingException e) { LOGGER.error(e.getMessage()); return success; } LOGGER.debug("Store Subscription: " + jsonMsg); Dictionary subMap = getSubscriptionMap(); subMap.put(subscriptionId, jsonMsg); setSubscriptionMap(subMap); //Set TTL (time to live) for subscription int ttlType = Calendar.MILLISECOND; String queryTtlType = queryMsg.getSubscriptionTtlType(); //If Query TTL Type is null, assume Milliseconds if (StringUtils.isBlank(queryTtlType)) { LOGGER.debug("Query TTL Type is null"); queryTtlType = TTL_TYPE_MILLISECONDS; } if (queryTtlType.equals(TTL_TYPE_MILLISECONDS)) { ttlType = Calendar.MILLISECOND; } else if (queryTtlType.equals(TTL_TYPE_SECONDS)) { ttlType = Calendar.SECOND; } else if (queryTtlType.equals(TTL_TYPE_MINUTES)) { ttlType = Calendar.MINUTE; } else if (queryTtlType.equals(TTL_TYPE_HOURS)) { ttlType = Calendar.HOUR; } else if (queryTtlType.equals(TTL_TYPE_MONTHS)) { ttlType = Calendar.MONTH; } else if (queryTtlType.equals(TTL_TYPE_YEARS)) { ttlType = Calendar.YEAR; } int queryTtl = queryMsg.getSubscriptionTtl(); LOGGER.debug("Query TTL: {}", queryTtl); if (queryTtl == -9 || queryTtl == 0) { //No TTL chosen; make it close to forever queryTtl = 9999; ttlType = Calendar.YEAR; } //Set TTL from creation time to TTL specified long creationTime = queryMsg.getCreationDate(); Calendar ttl = Calendar.getInstance(); ttl.setTimeInMillis(creationTime); ttl.add(ttlType, queryTtl); subscriptionTtlMap.put(subscriptionId, ttl); success = true; } else { LOGGER.trace("Catalog Framework or filter is NULL"); } } else { LOGGER.debug("Subscription ID is null: Subscription ID= {}", subscriptionId); } return success; }
From source file:com.echopf.ECHOFile.java
/** * {@.en Gets a remote file data.}/*w w w.j a v a2 s . c om*/ * {@.ja ??????} * @throws ECHOException */ public byte[] getRemoteBytes() throws ECHOException { // Get ready a background thread ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<byte[]> communicator = new Callable<byte[]>() { @Override public byte[] call() throws Exception { InputStream is = getRemoteInputStream(); int nRead; byte[] data = new byte[16384]; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } }; Future<byte[]> future = executor.submit(communicator); try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // ignore/reset } catch (ExecutionException e) { Throwable e2 = e.getCause(); throw new ECHOException(e2); } return null; }
From source file:com.emc.ecs.sync.CasMigrationTest.java
protected String summarize(FPPool pool, List<String> clipIds) throws Exception { List<String> summaries = Collections.synchronizedList(new ArrayList<String>()); ExecutorService service = Executors.newFixedThreadPool(CAS_THREADS); System.out.print("Summarizing clips"); for (String clipId : clipIds) { service.submit(new ClipReader(pool, clipId, summaries)); }//w ww. j a va 2 s . c o m service.shutdown(); service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES); service.shutdownNow(); System.out.println(); Collections.sort(summaries); StringBuilder out = new StringBuilder(); for (String summary : summaries) { out.append(summary); } return out.toString(); }
From source file:com.emc.vipr.sync.CasMigrationTest.java
protected String summarize(FPPool pool, List<String> clipIds) throws Exception { List<String> summaries = Collections.synchronizedList(new ArrayList<String>()); ExecutorService service = Executors.newFixedThreadPool(CAS_SETUP_THREADS); System.out.print("Summarizing clips"); for (String clipId : clipIds) { service.submit(new ClipReader(pool, clipId, summaries)); }/* w w w . j av a 2 s.c o m*/ service.shutdown(); service.awaitTermination(CAS_SETUP_WAIT_MINUTES, TimeUnit.MINUTES); service.shutdownNow(); System.out.println(); Collections.sort(summaries); StringBuilder out = new StringBuilder(); for (String summary : summaries) { out.append(summary); } return out.toString(); }
From source file:com.p2p.peercds.common.Torrent.java
private static String hashFiles(List<File> files) throws InterruptedException, IOException { int threads = getHashingThreadsCount(); ExecutorService executor = Executors.newFixedThreadPool(threads); ByteBuffer buffer = ByteBuffer.allocate(PIECE_LENGTH); List<Future<String>> results = new LinkedList<Future<String>>(); StringBuilder hashes = new StringBuilder(); long length = 0L; int pieces = 0; long start = System.nanoTime(); for (File file : files) { logger.info("Hashing data from {} with {} threads ({} pieces)...", new Object[] { file.getName(), threads, (int) (Math.ceil((double) file.length() / PIECE_LENGTH)) }); length += file.length();/*from w w w . j a v a 2 s. c o m*/ FileInputStream fis = new FileInputStream(file); FileChannel channel = fis.getChannel(); int step = 10; try { while (channel.read(buffer) > 0) { if (buffer.remaining() == 0) { buffer.clear(); results.add(executor.submit(new CallableChunkHasher(buffer))); } if (results.size() >= threads) { pieces += accumulateHashes(hashes, results); } if (channel.position() / (double) channel.size() * 100f > step) { logger.info(" ... {}% complete", step); step += 10; } } } finally { channel.close(); fis.close(); } } // Hash the last bit, if any if (buffer.position() > 0) { buffer.limit(buffer.position()); buffer.position(0); results.add(executor.submit(new CallableChunkHasher(buffer))); } pieces += accumulateHashes(hashes, results); // Request orderly executor shutdown and wait for hashing tasks to // complete. executor.shutdown(); while (!executor.isTerminated()) { Thread.sleep(10); } long elapsed = System.nanoTime() - start; int expectedPieces = (int) (Math.ceil((double) length / PIECE_LENGTH)); logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { files.size(), length, pieces, expectedPieces, String.format("%.1f", elapsed / 1e6), }); return hashes.toString(); }
From source file:ranktracker.crawler.youtube.YoutubeStatistics.java
@Override public void run() { ExecutorService executor = Executors.newFixedThreadPool(10); List<ProxyData> proxylist = objProxyDao.getProxyList(); try {/*from w w w .j ava2 s . c om*/ for (Videokeywords keywords : lstVideokeywords) { if (checkForRecentUpdatedKeyword(keywords)) { continue; } executor.submit(new VideoViewStatisticsThread(appContext, lstVideokeywords, objKeywordDao, yoUrl, dailyUrl, vimeoUrl, metacafeUrl, yoKeywordId, keywords, proxylist, fetchSourcewithAuthentication)); // yoUrl = keywords.getYoutubeURL(); // dailyUrl = keywords.getDailymotionURL(); // vimeoUrl = keywords.getVimeoURL(); // metacafeUrl = keywords.getMetacafeURL(); // yoKeywordId = keywords.getVideokeywordID(); // // System.out.println("yoKeywordId = " + yoKeywordId); // System.out.println("Youtube URL " + yoUrl); // // int youtube_view = 0; // int vimeo_view = 0; // int metacafe_view = 0; // int dailymotion_view = 0; // short daily_view = 0; // int last_count = 0; // // last_count = objKeywordDao.LastView(yoKeywordId); // System.out.println("-----------" + last_count + "----------"); // if (yoUrl.length() < 5) { // } else { // try { // if (yoUrl.contains("youtube.com")) { // // } else { // yoUrl = "youtube.com" + yoUrl; // } // String url = "http://www." + yoUrl; // int l = 0; // String input = fetchVideoPage(url); // while (input.length() <= 500 && l <= 3) { // input = fetchVideoPage(url); // l++; // } // // Document doc = Jsoup.parse(input); // { // Element links = doc.getElementById("watch7-views-info"); // String view = links.getElementsByClass("watch-view-count").text(); // // if (view.contains("views")) { // view = view.replaceAll(" views", ""); // } // if (view.contains(",")) { // youtube_view = Integer.parseInt(view.replaceAll(",", "")); // } else { // youtube_view = Integer.parseInt(view); // } // } // } catch (IOException | NumberFormatException e) { // e.printStackTrace(); // } // } // if (vimeoUrl.length() < 5) { // } else { // String url = "http://www." + vimeoUrl; // int l = 0; // String input = fetchVideoPage(url); // while (input.length() <= 500 && l <= 3) { // input = fetchVideoPage(url); // l++; // } // try { // Document doc = Jsoup.parse(input); // String links = doc.getElementById("cols").toString(); // // Pattern pattern = Pattern.compile("UserPlays:(.*?)/"); // Matcher matcher = pattern.matcher(links); // if (matcher.find()) { // String view = matcher.group(1).trim().replace('"', ' ').replaceAll(" ", ""); // if (view.contains(",")) { // vimeo_view = Integer.parseInt(view.replaceAll(",", "")); // } else { // vimeo_view = Integer.parseInt(view); // } // } // } catch (NumberFormatException e) { // e.printStackTrace(); // } // // } // // if (metacafeUrl.length() < 5) { // } else { // String url = "http://www." + metacafeUrl; // // try { // int l = 0; // String input = fetchVideoPage(url); // while (input.length() <= 500 && l <= 3) { // input = fetchVideoPage(url); // l++; // } // // Document doc = Jsoup.parse(input); // String[] links = doc.getElementById("Views").text().split(" "); // String view = (links[0]); // if (view.contains(",")) { // metacafe_view = Integer.parseInt(view.replaceAll(",", "")); // } else { // metacafe_view = Integer.parseInt(view); // } // // } catch (IOException | NumberFormatException e) { // e.printStackTrace(); // } // } // // if (dailyUrl.length() < 5) { // } else { // try { // String url = "http://www." + dailyUrl; // int l = 0; // String input = fetchVideoPage(url); // while (input.length() <= 1000 && l <= 3) { // input = fetchVideoPage(url); // l++; // } // Document doc = Jsoup.parse(input); // String[] links = doc.getElementById("video_views_count").text().split(" "); // String view = links[0]; // if (view.contains(",")) { // dailymotion_view = Integer.parseInt(view.replaceAll(",", "")); // } else { // dailymotion_view = Integer.parseInt(view); // } // // } catch (IOException | NumberFormatException e) { // e.printStackTrace(); // } // } // System.out.println("youtube_view" + youtube_view); // System.out.println("vimeo_view" + vimeo_view); // System.out.println("metacafe_view" + metacafe_view); // System.out.println("dailymotion_view" + dailymotion_view); // System.out.println("last_count" + last_count); // // int daily_view_count = youtube_view - last_count; // if (daily_view_count >= youtube_view || daily_view_count >= 65535) { // daily_view_count = 0; // } // if (youtube_view <= last_count) { // daily_view_count = 0; // } // // daily_view = (short) (daily_view_count); // System.out.println("daily_view" + daily_view); // // objKeywordDao.saveYoutubeStatistics(yoKeywordId, youtube_view, vimeo_view, metacafe_view, dailymotion_view, daily_view); // System.out.println("==============inserted================"); } } catch (Exception ex) { Logger.getLogger(YoutubeStatistics.class.getName()).log(Level.SEVERE, null, ex); } executor.shutdown(); try { executor.awaitTermination(10, TimeUnit.MINUTES); } catch (InterruptedException ex) { Logger.getLogger(Vimeo_search.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.jayway.maven.plugins.android.AbstractEmulatorMojo.java
/** * Sends a user command to the running emulator via its telnet interface. * * @param port The emulator's telnet port. * @param command The command to execute on the emulator's telnet interface. * @return Whether sending the command succeeded. */// ww w . j a va2 s.c o m private boolean sendEmulatorCommand( //final Launcher launcher, //final PrintStream logger, final int port, final String command) { Callable<Boolean> task = new Callable<Boolean>() { public Boolean call() throws IOException { Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket("127.0.0.1", port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (in.readLine() == null) { return false; } out.write(command); out.write("\r\n"); } finally { try { out.close(); in.close(); socket.close(); } catch (Exception e) { // Do nothing } } return true; } private static final long serialVersionUID = 1L; }; boolean result = false; try { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Boolean> future = executor.submit(task); result = future.get(); } catch (Exception e) { getLog().error(String.format("Failed to execute emulator command '%s': %s", command, e)); } return result; }