List of usage examples for java.util.concurrent Future get
V get() throws InterruptedException, ExecutionException;
From source file:com.glaf.core.resource.ResourceFactory.java
public static byte[] getData(final String region, final String key) { if (conf.getBoolean(DISTRIBUTED_ENABLED, false)) { String regionName = Environment.getCurrentSystemName() + "_res_" + region; String complexKey = Environment.getCurrentSystemName() + "_res_" + key; if (SystemProperties.getDeploymentSystemName() != null) { regionName = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName() + "_res_" + region; }/* w ww .j a va 2s. c o m*/ if (SystemProperties.getDeploymentSystemName() != null) { complexKey = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName() + "_res_" + key; } final String regionName2 = regionName; final String complexKey2 = complexKey; boolean waitFor = true; Callable<byte[]> task = new Callable<byte[]>() { @Override public byte[] call() throws Exception { return channel.getData(regionName2, complexKey2); } }; try { Future<byte[]> result = pool.submit(task); long start = System.currentTimeMillis(); // ? if (waitFor) { while (true) { if (System.currentTimeMillis() - start > 2000) { break; } if (result.isDone()) { return result.get(); } } } } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } } return null; }
From source file:it.units.malelab.ege.util.Utils.java
public static <T> List<T> getAll(List<Future<List<T>>> futures) throws InterruptedException, ExecutionException { List<T> results = new ArrayList<>(); for (Future<List<T>> future : futures) { results.addAll(future.get()); }/*from w ww. j a v a2 s. c om*/ return results; }
From source file:com.glaf.core.config.ConfigFactory.java
public static String getString(final String region, final String key) { if (conf.getBoolean(DISTRIBUTED_ENABLED, false)) { String regionName = Environment.getCurrentSystemName() + "_" + region; String complexKey = Environment.getCurrentSystemName() + "_" + key; if (SystemProperties.getDeploymentSystemName() != null) { regionName = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName() + "_" + region; }/* ww w . ja va 2 s.c om*/ if (SystemProperties.getDeploymentSystemName() != null) { complexKey = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName() + "_" + key; } final String regionName2 = regionName; final String complexKey2 = complexKey; boolean waitFor = true; Callable<String> task = new Callable<String>() { @Override public String call() throws Exception { return channel.getString(regionName2, complexKey2); } }; try { Future<String> result = pool.submit(task); long start = System.currentTimeMillis(); // ? if (waitFor) { while (true) { if (System.currentTimeMillis() - start > 2000) { break; } if (result.isDone()) { return result.get(); } } } } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } } return null; }
From source file:com.glaf.core.cache.CacheFactory.java
public static String getString(final String key) { boolean waitFor = true; Callable<String> task = new Callable<String>() { @Override/*from www . j ava 2s . c o m*/ public String call() throws Exception { try { Cache cache = getCache(); if (cache != null) { String cacheKey = Environment.getCurrentSystemName() + "_" + CACHE_PREFIX + key; if (SystemProperties.getDeploymentSystemName() != null) { cacheKey = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName() + "_" + CACHE_PREFIX + key; } cacheKey = DigestUtils.md5Hex(cacheKey.getBytes()); Object value = cache.get(cacheKey); if (value != null) { logger.debug("get object'" + key + "' from cache."); return value.toString(); } } } catch (Exception ex) { if (logger.isDebugEnabled()) { ex.printStackTrace(); logger.debug(ex); } } return null; } }; try { Future<String> result = pool.submit(task); long start = System.currentTimeMillis(); // ? if (waitFor) { while (true) { if (System.currentTimeMillis() - start > 2000) { break; } if (result.isDone()) { return result.get(); } } } } catch (Exception e) { logger.error(e); } return null; }
From source file:it.geosolutions.tools.io.file.Copy.java
/** * Copy a list of files (preserving data) to a destination (which can be on * nfs) waiting (at least) 'seconds' seconds for each file propagation. * /* w w w . j a v a 2s .c o m*/ * @param es * The ExecutorService or null if you want to use a * CachedThreadPool. * @note potentially this is a bad executor (for log lists of big files) * NOTE: we should make some tests on this 22 Aug 2011 * @param list * @param baseDestDir * @param overwrite * if false and destination exists() do not overwrite the file * @param seconds * @return the resulting moved file list or null * */ public static List<File> parallelCopyListFileToNFS(ExecutorService es, final List<File> list, final File baseDestDir, final int seconds) { try { /* * this could be potentially a bad executor (for log lists of big * files) NOTE: we should make some tests on this 22 Aug 2011 */ if (es == null) { final ThreadFactory threadFactory = Executors.defaultThreadFactory(); es = Executors.newCachedThreadPool(threadFactory); } final List<FutureTask<File>> futureFileList = asynchCopyListFileToNFS(es, list, baseDestDir, seconds); // list if (futureFileList == null) { if (LOGGER.isErrorEnabled()) LOGGER.error("Failed to copy files."); return null; } final int size = futureFileList.size(); if (size == 0) { if (LOGGER.isErrorEnabled()) LOGGER.error("Failed to copy file list using an empty list"); return null; } final List<File> ret = new ArrayList<File>(size); for (Future<File> futureFile : futureFileList) { if (futureFile != null) { File file; try { file = futureFile.get(); if (file != null && file.exists()) { ret.add(file); } else { if (LOGGER.isWarnEnabled()) LOGGER.warn("SKIPPING file:\n\t" + file + ".\nUnable to copy a not existent file."); } } catch (InterruptedException e) { if (LOGGER.isErrorEnabled()) LOGGER.error("Unable to get the file from this future File copy. ", e); } catch (ExecutionException e) { if (LOGGER.isErrorEnabled()) LOGGER.error("Unable to get the file from this future File copy. ", e); } } } return ret; } catch (Throwable t) { if (LOGGER.isErrorEnabled()) LOGGER.error("Unrecognized error occurred. ", t); } finally { if (es != null) es.shutdownNow(); } return null; }
From source file:com.echopf.ECHOQuery.java
/** * Does Find objects from the remote server. * @param sync : if set TRUE, then the main (UI) thread is waited for complete the finding in a background thread. * (a synchronous communication) * @param listKey the key associated with the object list * @param clazz the object class//from w w w . j a v a2s .co m * @param callback invoked after the finding is completed * @param instanceId the reference ID of the finding target instance * @param resourceType the type of this object * @param params to control the output objects * @throws ECHOException */ public static <T extends ECHODataObject<T>> ECHOList<T> doFind(final boolean sync, final String listKey, final String resourceType, final FindCallback<T> callback, final String instanceId, final JSONObject fParams, final ECHODataObjectFactory<T> factory) throws ECHOException { // Get ready a background thread final Handler handler = new Handler(); ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<ECHOList<T>> communicator = new Callable<ECHOList<T>>() { @Override public ECHOList<T> call() throws ECHOException { ECHOException exception = null; ECHOList<T> objList = null; try { JSONObject response = getRequest(instanceId + "/" + resourceType, fParams); /* begin copying data */ objList = new ECHOList<T>(response.optJSONObject("paginate")); JSONArray items = response.optJSONArray(listKey); if (items == null) throw new ECHOException(0, "Invalid data type for response-field `" + listKey + "`."); for (int i = 0; i < items.length(); i++) { JSONObject item = items.optJSONObject(i); if (item == null) throw new ECHOException(0, "Invalid data type for response-field `" + listKey + "`."); String refid = item.optString("refid"); if (refid.isEmpty()) continue; T obj = factory.create(instanceId, refid, item); objList.add(obj); } /* end copying data */ } catch (ECHOException e) { exception = e; } catch (Exception e) { exception = new ECHOException(e); } if (sync == false) { // Execute a callback method in the main (UI) thread. if (callback != null) { final ECHOException fException = exception; final ECHOList<T> fObjList = objList; handler.post(new Runnable() { @Override public void run() { callback.done(fObjList, fException); } }); } return null; } else { if (exception == null) return objList; throw exception; } } }; Future<ECHOList<T>> future = executor.submit(communicator); if (sync) { try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // ignore/reset } catch (ExecutionException e) { Throwable e2 = e.getCause(); if (e2 instanceof ECHOException) { throw (ECHOException) e2; } throw new RuntimeException(e2); } } return null; }
From source file:httpasync.AsyncClientPipelinedStreaming.java
public static void a() { long start = System.currentTimeMillis(); CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining(); try {/*from ww w.ja v a 2s. co m*/ httpclient.start(); HttpHost targetHost = new HttpHost("globalquotes.xignite.com", 80); // HttpGet[] resquests = { // new HttpGet("/docs/index.html"), // new HttpGet("/docs/introduction.html"), // new HttpGet("/docs/setup.html"), // new HttpGet("/docs/config/index.html") // }; List<MyRequestProducer> requestProducers = new ArrayList<MyRequestProducer>(); List<MyResponseConsumer> responseConsumers = new ArrayList<MyResponseConsumer>(); String[] codes = StockParser.stockCodeList.split(","); // 500 * 17 ~~~~~~~~~~~~~~~ Shutting down : 12660 // avg=17348.1 // 400 * 21 ~~~~~~~~~~~~~~~ Shutting down : 27476 // avg=18923.8 int take = 400; for (int i = 0; i < codes.length / take; i++) { String code = Arrays.asList(codes).stream().skip(i * take).limit(take) .collect(Collectors.joining(",")); HttpGet request = new HttpGet(StockParser.uri + URLEncoder.encode(code.trim())); requestProducers.add(new MyRequestProducer(targetHost, request)); responseConsumers.add(new MyResponseConsumer(request)); } // System.out.println("? = "+ responseConsumers.size()); // for (HttpGet request: resquests) { // requestProducers.add(new MyRequestProducer(targetHost, request)); // responseConsumers.add(new MyResponseConsumer(request)); // } Future<List<Boolean>> future = httpclient.execute(targetHost, requestProducers, responseConsumers, new FutureCallback<List<Boolean>>() { @Override public void completed(List<Boolean> result) { } @Override public void failed(Exception ex) { ex.printStackTrace(); } @Override public void cancelled() { } }); future.get(); System.out.println(take + " * " + responseConsumers.size() + " ~~~~~~~~~~~~~~~ Shutting down : " + (System.currentTimeMillis() - start)); } catch (Exception e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } // System.out.println("Done"); }
From source file:com.dilmus.dilshad.scabi.core.async.DComputeNoBlock.java
public static HttpResponse get(Future<HttpResponse> future) throws InterruptedException, ExecutionException, TimeoutException { HttpResponse httpResponse = null;/* w ww .j ava2s . c o m*/ httpResponse = future.get(); return httpResponse; }
From source file:com.bittorrent.mpetazzoni.common.Torrent.java
/** * Accumulate the piece hashes into a given {@link StringBuilder}. * * @param hashes The {@link StringBuilder} to append hashes to. * @param results The list of {@link Future}s that will yield the piece * hashes./*from w w w. j a v a 2s .c om*/ */ private static int accumulateHashes(StringBuilder hashes, List<Future<String>> results) throws InterruptedException, IOException { try { int pieces = results.size(); for (Future<String> chunk : results) { hashes.append(chunk.get()); } results.clear(); return pieces; } catch (ExecutionException ee) { throw new IOException("Error while hashing the torrent data!", ee); } }
From source file:com.taobao.android.tpatch.utils.SmaliUtils.java
/** * dex?smali//w w w . j a v a 2 s .c o m * @param dex * @param outputDir * @param includeClasses ?? */ public static boolean disassembleDexFile(File dex, File outputDir, final Set<String> includeClasses) throws IOException { final baksmaliOptions options = createBaksmaliOptions(); if (!outputDir.exists()) { outputDir.mkdirs(); } DexFile dexFile = DexFileFactory.loadDexFile(dex, DEFAULT_API_LEVEL, true); options.outputDirectory = outputDir.getAbsolutePath(); //1. options.jobs = 3; if (options.registerInfo != 0 || options.deodex) { try { Iterable<String> extraClassPathEntries; if (options.extraClassPathEntries != null) { extraClassPathEntries = options.extraClassPathEntries; } else { extraClassPathEntries = ImmutableList.of(); } options.classPath = ClassPath.fromClassPath(options.bootClassPathDirs, Iterables.concat(options.bootClassPathEntries, extraClassPathEntries), dexFile, options.apiLevel, options.checkPackagePrivateAccess, options.experimental); if (options.customInlineDefinitions != null) { options.inlineResolver = new CustomInlineMethodResolver(options.classPath, options.customInlineDefinitions); } } catch (Exception ex) { System.err.println("\n\nError occurred while loading boot class path files. Aborting."); ex.printStackTrace(System.err); return false; } } if (options.resourceIdFileEntries != null) { class PublicHandler extends DefaultHandler { String prefix = null; public PublicHandler(String prefix) { super(); this.prefix = prefix; } public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException { if (qName.equals("public")) { String type = attr.getValue("type"); String name = attr.getValue("name").replace('.', '_'); Integer public_key = Integer.decode(attr.getValue("id")); String public_val = new StringBuffer().append(prefix).append(".").append(type).append(".") .append(name).toString(); options.resourceIds.put(public_key, public_val); } } } ; for (Map.Entry<String, String> entry : options.resourceIdFileEntries.entrySet()) { try { SAXParser saxp = SAXParserFactory.newInstance().newSAXParser(); String prefix = entry.getValue(); saxp.parse(entry.getKey(), new PublicHandler(prefix)); } catch (ParserConfigurationException e) { continue; } catch (SAXException e) { continue; } catch (IOException e) { continue; } } } File outputDirectoryFile = new File(options.outputDirectory); if (!outputDirectoryFile.exists()) { if (!outputDirectoryFile.mkdirs()) { System.err.println("Can't create the output directory " + options.outputDirectory); return false; } } // sort the classes, so that if we're on a case-insensitive file system and need to handle classes with file // name collisions, then we'll use the same name for each class, if the dex file goes through multiple // baksmali/smali cycles for some reason. If a class with a colliding name is added or removed, the filenames // may still change of course List<? extends ClassDef> classDefs = Ordering.natural().sortedCopy(dexFile.getClasses()); if (!options.noAccessorComments) { options.syntheticAccessorResolver = new SyntheticAccessorResolver(classDefs); } final ClassFileNameHandler fileNameHandler = new ClassFileNameHandler(outputDirectoryFile, ".smali"); ExecutorService executor = Executors.newFixedThreadPool(options.jobs); List<Future<Boolean>> tasks = Lists.newArrayList(); for (final ClassDef classDef : classDefs) { tasks.add(executor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { String className = getDalvikClassName(classDef.getType()); if (null != includeClasses) { if (includeClasses.contains(className)) { BakSmali.disassembleClass(classDef, fileNameHandler, options); } return true; } else { return BakSmali.disassembleClass(classDef, fileNameHandler, options); } } })); } boolean errorOccurred = false; try { for (Future<Boolean> task : tasks) { while (true) { try { if (!task.get()) { errorOccurred = true; } } catch (InterruptedException ex) { continue; } catch (ExecutionException ex) { throw new RuntimeException(ex); } break; } } } finally { executor.shutdown(); } return !errorOccurred; }