List of usage examples for java.util.concurrent FutureTask FutureTask
public FutureTask(Callable<V> callable)
From source file:org.apache.jackrabbit.oak.plugins.segment.CompactionAndCleanupIT.java
private static <T> T run(Callable<T> callable) throws InterruptedException, ExecutionException { FutureTask<T> task = new FutureTask<T>(callable); new Thread(task).start(); return task.get(); }
From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java
/** * Fetches all existing categories from the server, parses them and adds new ones to the * {@link SessionSingleton}. Duplicates do not get added *//*from w ww .j a va 2 s. c o m*/ public ArrayList<Category> getCategories() throws ExecutionException, InterruptedException { Callable<ArrayList<Category>> categoriesCallable = new Callable<ArrayList<Category>>() { @Override public ArrayList<Category> call() throws Exception { String jsonString = getMethod("http://www.balticapp.fi/lukeA/category"); JSONArray jsonArr = new JSONArray(jsonString); return LukeUtils.getCategoryObjectsFromJsonArray(jsonArr); } }; FutureTask<ArrayList<Category>> arrayListFutureTask = new FutureTask<ArrayList<Category>>( categoriesCallable); Thread t = new Thread(arrayListFutureTask); t.start(); return arrayListFutureTask.get(); }
From source file:org.jdesktop.swingworker.AccumulativeRunnable.java
/** * Constructs this {@code SwingWorker}./*from w ww . ja v a 2s. c om*/ */ public SwingWorker() { Callable<T> callable = new Callable<T>() { public T call() throws Exception { setState(StateValue.STARTED); return doInBackground(); } }; future = new FutureTask<T>(callable) { @Override protected void done() { doneEDT(); setState(StateValue.DONE); } }; state = StateValue.PENDING; propertyChangeSupport = new SwingWorkerPropertyChangeSupport(this); doProcess = null; doNotifyProgressChange = null; }
From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java
/** * Fetches the currently logged user from the server * @return User object corresponding to the currently logged user * @throws IOException//from w ww . j a v a 2 s . co m * @throws ExecutionException * @throws InterruptedException */ public UserFromServer getOwnUser() throws IOException, ExecutionException, InterruptedException { Callable<UserFromServer> userFromServerCallable = new Callable<UserFromServer>() { @Override public UserFromServer call() throws Exception { String jsonString = getMethod("http://www.balticapp.fi/lukeA/user/me"); JSONObject jsonObject = new JSONObject(jsonString); return LukeUtils.parseUserFromJsonObject(jsonObject); } }; FutureTask<UserFromServer> userFromServerFutureTask = new FutureTask<UserFromServer>( userFromServerCallable); Thread t = new Thread(userFromServerFutureTask); t.start(); return userFromServerFutureTask.get(); }
From source file:org.apache.tika.parser.ocr.TesseractOCRParser.java
/** * Run external tesseract-ocr process./* ww w. j a v a2s. c o m*/ * * @param input * File to be ocred * @param output * File to collect ocr result * @param config * Configuration of tesseract-ocr engine * @throws TikaException * if the extraction timed out * @throws IOException * if an input error occurred */ private void doOCR(File input, File output, TesseractOCRConfig config) throws IOException, TikaException { String[] cmd = { config.getTesseractPath() + getTesseractProg(), input.getPath(), output.getPath(), "-l", config.getLanguage(), "-psm", config.getPageSegMode(), config.getOutputType().name().toLowerCase(Locale.US), "-c", (config.getPreserveInterwordSpacing()) ? "preserve_interword_spaces=1" : "preserve_interword_spaces=0" }; ProcessBuilder pb = new ProcessBuilder(cmd); setEnv(config, pb); final Process process = pb.start(); process.getOutputStream().close(); InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); logStream("OCR MSG", out, input); logStream("OCR ERROR", err, input); FutureTask<Integer> waitTask = new FutureTask<>(new Callable<Integer>() { public Integer call() throws Exception { return process.waitFor(); } }); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(config.getTimeout(), TimeUnit.SECONDS); } catch (InterruptedException e) { waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); throw new TikaException("TesseractOCRParser interrupted", e); } catch (ExecutionException e) { // should not be thrown } catch (TimeoutException e) { waitThread.interrupt(); process.destroy(); throw new TikaException("TesseractOCRParser timeout", e); } }
From source file:ubic.gemma.core.apps.ShellDelegatingBlat.java
/** * @param querySequenceFile query sequence file * @param outputPath output path/*from w w w . j a va 2 s . com*/ * @return processed results. */ private Collection<BlatResult> jniGfClientCall(final File querySequenceFile, final String outputPath, final int portToUse) throws IOException { try { ShellDelegatingBlat.log.debug("Starting blat run"); FutureTask<Boolean> blatThread = new FutureTask<>(new Callable<Boolean>() { @Override public Boolean call() { ShellDelegatingBlat.this.GfClientCall(host, Integer.toString(portToUse), seqDir, querySequenceFile.getPath(), outputPath); return true; } }); ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(blatThread); executor.shutdown(); // wait... StopWatch overallWatch = new StopWatch(); overallWatch.start(); while (!blatThread.isDone()) { try { Thread.sleep(ShellDelegatingBlat.BLAT_UPDATE_INTERVAL_MS); } catch (InterruptedException ie) { throw new RuntimeException(ie); } this.outputFile(outputPath, overallWatch); } overallWatch.stop(); String minutes = TimeUtil.getMinutesElapsed(overallWatch); ShellDelegatingBlat.log.info("Blat took a total of " + minutes + " minutes"); } catch (UnsatisfiedLinkError e) { ShellDelegatingBlat.log.error(e, e); ShellDelegatingBlat.log.info("Falling back on exec()"); this.execGfClient(querySequenceFile, outputPath, portToUse); } return this.processPsl(outputPath, null); }
From source file:edu.cmu.graphchi.engine.HypergraphChiEngine.java
/** * Runs the GraphChi program for given number of iterations. <b>Note:</b> Prior to calling this, * you must have set the edge-data and vertex-data converters: * setEdataConverter()/*from w w w . j a v a 2 s .co m*/ * setVertexDataConverter() * @param program yoru GraphChi program * @param niters number of iterations * @throws IOException */ public void run(HypergraphChiProgram<VertexDataType, EdgeDataType> program, int niters) throws IOException { if (!hasSetEdgeDataConverter) { throw new IllegalStateException("You need to call setEdataConverter() prior to calling run()!"); } if (!hasSetVertexDataConverter) { throw new IllegalStateException("You need to call setVertexDataConverter() prior to calling run()!"); } int nprocs = 4; if (Runtime.getRuntime().availableProcessors() > nprocs) { nprocs = Runtime.getRuntime().availableProcessors(); } if (System.getProperty("num_threads") != null) nprocs = Integer.parseInt(System.getProperty("num_threads")); logger.info(":::::::: Using " + nprocs + " execution threads :::::::::"); parallelExecutor = Executors.newFixedThreadPool(nprocs); loadingExecutor = Executors.newFixedThreadPool(4); chiContext.setNumIterations(niters); long startTime = System.currentTimeMillis(); initializeSlidingShards(); if (enableScheduler) { initializeScheduler(); chiContext.setScheduler(scheduler); scheduler.addAllTasks(); logger.info("Using scheduler!"); } else { chiContext.setScheduler(new MockScheduler()); } if (disableInEdges) { ChiVertex.disableInedges = true; } if (disableOutEdges) { ChiVertex.disableOutedges = true; } /* Initialize vertex-data handler */ if (vertexDataConverter != null) { vertexDataHandler = new VertexData<VertexDataType>(numVertices(), baseFilename, vertexDataConverter, true); vertexDataHandler.setBlockManager(blockManager); } chiContext.setNumEdges(numEdges()); for (int iter = 0; iter < niters; iter++) { /* Wait for executor have finished all writes */ while (!blockManager.empty()) { try { Thread.sleep(50); } catch (InterruptedException ie) { } } blockManager.reset(); chiContext.setIteration(iter); chiContext.setNumVertices(numVertices()); program.beginIteration(chiContext); if (scheduler != null) { if (iter > 0 && !scheduler.hasTasks()) { logger.info("No new tasks to run. Terminating."); break; } scheduler.reset(); } for (int execInterval = 0; execInterval < nShards; ++execInterval) { int intervalSt = intervals.get(execInterval).getFirstVertex(); int intervalEn = intervals.get(execInterval).getLastVertex(); logger.info((System.currentTimeMillis() - startTime) * 0.001 + "s: iteration: " + iter + ", interval: " + intervalSt + " -- " + intervalEn); if (program instanceof PigGraphChiBase) { ((PigGraphChiBase) program).setStatusString("GraphChi iteration " + iter + " / " + (niters - 1) + ";" + " vertex interval:" + intervalSt + " -- " + intervalEn); } program.beginInterval(chiContext, intervals.get(execInterval)); MemoryShard<EdgeDataType> memoryShard = null; if (!disableInEdges) { if (!onlyAdjacency || !autoLoadNext || nextWindow == null) { if (!disableOutEdges) slidingShards.get(execInterval).flush(); // MESSY! memoryShard = createMemoryShard(intervalSt, intervalEn, execInterval); } else { memoryShard = null; } } subIntervalStart = intervalSt; while (subIntervalStart <= intervalEn) { int adjMaxWindow = maxWindow; if (Integer.MAX_VALUE - subIntervalStart < maxWindow) adjMaxWindow = Integer.MAX_VALUE - subIntervalStart - 1; if (anyVertexScheduled(subIntervalStart, Math.min(intervalEn, subIntervalStart + adjMaxWindow))) { ChiVertex<VertexDataType, EdgeDataType>[] vertices = null; int vertexBlockId = -1; if (!autoLoadNext || nextWindow == null) { try { subIntervalEnd = determineNextWindow(subIntervalStart, Math.min(intervalEn, subIntervalStart + adjMaxWindow)); } catch (NoEdgesInIntervalException nie) { logger.info("No edges, skip: " + subIntervalStart + " -- " + subIntervalEnd); subIntervalEnd = subIntervalStart + adjMaxWindow; subIntervalStart = subIntervalEnd + 1; continue; } int nvertices = subIntervalEnd - subIntervalStart + 1; logger.info("Subinterval:: " + subIntervalStart + " -- " + subIntervalEnd + " (iteration " + iter + ")"); vertices = new ChiVertex[nvertices]; logger.info("Init vertices..."); vertexBlockId = initVertices(nvertices, subIntervalStart, vertices); logger.info("Loading..."); long t0 = System.currentTimeMillis(); loadBeforeUpdates(execInterval, vertices, memoryShard, subIntervalStart, subIntervalEnd); logger.info("Load took: " + (System.currentTimeMillis() - t0) + "ms"); } else { /* This is a mess! */ try { long tf = System.currentTimeMillis(); final TimerContext _timer = waitForFutureTimer.time(); IntervalData next = nextWindow.get(); memoryShard = next.getMemShard(); _timer.stop(); logger.info("Waiting for future task loading took " + (System.currentTimeMillis() - tf) + " ms"); if (subIntervalStart != next.getSubInterval().getFirstVertex()) throw new IllegalStateException( "Future loaders interval does not match the expected one! " + subIntervalStart + " != " + next.getSubInterval().getFirstVertex()); subIntervalEnd = next.getSubInterval().getLastVertex(); vertexBlockId = next.getVertexBlockId(); vertices = next.getVertices(); nextWindow = null; } catch (Exception err) { throw new RuntimeException(err); } } if (autoLoadNext) { /* Start a future for loading the next window */ adjMaxWindow = maxWindow; if (Integer.MAX_VALUE - subIntervalEnd < maxWindow) adjMaxWindow = Integer.MAX_VALUE - subIntervalEnd - 1; if (subIntervalEnd + 1 <= intervalEn) { nextWindow = new FutureTask<IntervalData>(new AutoLoaderTask( new VertexInterval(subIntervalEnd + 1, Math.min(intervalEn, subIntervalEnd + 1 + adjMaxWindow)), execInterval, memoryShard)); } else if (execInterval < nShards - 1) { int nextIntervalSt = intervals.get(execInterval + 1).getFirstVertex(); int nextIntervalEn = intervals.get(execInterval + 1).getLastVertex(); slidingShards.get(execInterval).setOffset(memoryShard.getStreamingOffset(), memoryShard.getStreamingOffsetVid(), memoryShard.getStreamingOffsetEdgePtr()); nextWindow = new FutureTask<IntervalData>( new AutoLoaderTask( new VertexInterval(nextIntervalSt, Math.min(nextIntervalEn, nextIntervalSt + 1 + adjMaxWindow)), execInterval + 1, createMemoryShard(nextIntervalSt, nextIntervalEn, execInterval + 1))); } if (nextWindow != null) loadingExecutor.submit(nextWindow); } /* Clear scheduler bits */ if (scheduler != null) scheduler.removeTasks(subIntervalStart, subIntervalEnd); chiContext.setCurInterval(new VertexInterval(subIntervalStart, subIntervalEnd)); program.beginSubInterval(chiContext, new VertexInterval(subIntervalStart, subIntervalEnd)); long t1 = System.currentTimeMillis(); execUpdates(program, vertices); logger.info("Update exec: " + (System.currentTimeMillis() - t1) + " ms."); // Write vertices (async) final int _firstVertex = subIntervalStart; final int _blockId = vertexBlockId; parallelExecutor.submit(new Runnable() { @Override public void run() { try { vertexDataHandler.releaseAndCommit(_firstVertex, _blockId); } catch (IOException ioe) { ioe.printStackTrace(); } } }); subIntervalStart = subIntervalEnd + 1; program.endSubInterval(chiContext, new VertexInterval(subIntervalStart, subIntervalEnd)); } else { subIntervalEnd = subIntervalStart + adjMaxWindow; logger.info("Skipped interval - no vertices scheduled. " + subIntervalStart + " -- " + subIntervalEnd); subIntervalStart = subIntervalEnd + 1; } } /* Commit */ if (!disableInEdges) { memoryShard.commitAndRelease(modifiesInedges, modifiesOutedges); if (!disableOutEdges && !autoLoadNext) { slidingShards.get(execInterval).setOffset(memoryShard.getStreamingOffset(), memoryShard.getStreamingOffsetVid(), memoryShard.getStreamingOffsetEdgePtr()); } } } for (SlidingShard shard : slidingShards) { shard.flush(); shard.setOffset(0, 0, 0); } program.endIteration(chiContext); } // Iterations parallelExecutor.shutdown(); loadingExecutor.shutdown(); if (vertexDataHandler != null) vertexDataHandler.close(); logger.info("Engine finished in: " + (System.currentTimeMillis() - startTime) * 0.001 + " secs."); logger.info("Updates: " + nupdates); }
From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java
/** * Attempts to log in into the Luke server. If succesful, starts a task to fetch users data * @param welcomeActivity/* w w w . ja va2 s .c o m*/ * @param idToken */ public void attemptLogin(final WelcomeActivity welcomeActivity, final String idToken) { Callable<Boolean> booleanCallable = new Callable<Boolean>() { @Override public Boolean call() throws Exception { try { URL lukeURL = new URL(welcomeActivity.getString(R.string.loginUrl)); HttpURLConnection httpURLConnection = (HttpURLConnection) lukeURL.openConnection(); httpURLConnection.setRequestProperty(welcomeActivity.getString(R.string.authorization), welcomeActivity.getString(R.string.bearer) + idToken); if (httpURLConnection.getResponseCode() == 200) { return true; } else { Log.e(TAG, "call: LOGIN DIDN'T WORK"); // TODO: 12/12/2016 DANIEL return false; } } catch (MalformedURLException e) { Log.e(TAG, "call: ", e); return false; } catch (IOException e) { Log.e(TAG, "call: ", e); return false; } } }; FutureTask<Boolean> booleanFutureTask = new FutureTask<>(booleanCallable); Thread thread = new Thread(booleanFutureTask); thread.start(); try { if (booleanFutureTask.get()) { startFetchUserDataTask(welcomeActivity); } else { Log.e(TAG, "onAuthentication: booleanFutureTask failed"); } } catch (InterruptedException | ExecutionException e) { Log.e(TAG, "onAuthentication: ", e); } }
From source file:ru.valle.btc.MainActivityTest.java
private String getText(final Activity activity, final int id) { FutureTask<String> task = new FutureTask<>(new Callable<String>() { @Override/*from w w w. j a v a 2s . co m*/ public String call() throws Exception { TextView textView = ((TextView) activity.findViewById(id)); return textView.getVisibility() == View.VISIBLE ? getString(textView) : null; } }); activity.runOnUiThread(task); try { return task.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; }
From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java
/** * Fetches the newest link from the backend. This link will be shown at the start of the app. * Only the newest link will be shown/* w ww . j ava2 s . c o m*/ * @return Link object of the newest link on the backend */ public Link getNewestLink() { Callable<Link> linkCallable = new Callable<Link>() { @Override public Link call() throws Exception { String jsonString = getMethod("http://www.balticapp.fi/lukeA/link"); JSONArray jsonArray = new JSONArray(jsonString); Log.e(TAG, "getlinks call: jsonArray" + jsonArray.toString()); List<Link> links = LukeUtils.parseLinksFromJsonArray(jsonArray); return links.get(links.size() - 1); } }; FutureTask<Link> linkFutureTask = new FutureTask<>(linkCallable); Thread t = new Thread(linkFutureTask); t.start(); try { return linkFutureTask.get(); } catch (InterruptedException | ExecutionException e) { Log.e(TAG, "reportSubmission: ", e); return null; } }