List of usage examples for java.util.concurrent FutureTask cancel
public boolean cancel(boolean mayInterruptIfRunning)
From source file:uk.ac.kcl.iop.brc.core.pipeline.common.service.DocumentConversionService.java
private File makeTiffFromPDF(DNCWorkCoordinate coordinate, File input) throws IOException, TikaException { File output = File.createTempFile(coordinate.getFileName(), ".tiff"); String[] cmd = { getImageMagickProg(), "-density", "300", input.getPath(), "-depth", "8", "-quality", "1", output.getPath() };/*from w ww . ja va 2 s . co m*/ Process process = new ProcessBuilder(cmd).start(); IOUtils.closeQuietly(process.getOutputStream()); InputStream processInputStream = process.getInputStream(); logStream(processInputStream); FutureTask<Integer> waitTask = new FutureTask<>(process::waitFor); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(240, TimeUnit.SECONDS); return output; } catch (Exception e) { logger.error(e.getMessage()); waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); waitTask.cancel(true); } finally { IOUtils.closeQuietly(processInputStream); process.destroy(); waitThread.interrupt(); waitTask.cancel(true); } return null; }
From source file:ubic.gemma.loader.util.fetcher.AbstractFetcher.java
/** * @param future/*from w ww.j av a2s . c om*/ * @return true if it finished normally, false if it was cancelled. */ protected boolean waitForDownload(FutureTask<Boolean> future) { StopWatch timer = new StopWatch(); timer.start(); long lastTime = timer.getTime(); while (!future.isDone() && !future.isCancelled()) { try { Thread.sleep(INFO_UPDATE_INTERVAL); } catch (InterruptedException ie) { log.info("Cancelling download"); boolean cancelled = future.cancel(true); if (cancelled) { log.info("Download stopped successfully."); return false; } throw new RuntimeException("Cancellation failed."); } if (log.isInfoEnabled() && timer.getTime() > (lastTime + 2000L)) { log.info("Waiting ... " + timer.getTime() + "ms elapsed...."); } } return true; }
From source file:pt.webdetails.cpf.messaging.EventPublisher.java
private Runnable getPublishAndLogTask(final PluginEvent event) { Runnable publishAndLog = new Runnable() { @Override//from w w w.j a v a 2 s.c om public void run() { FutureTask<Result> toRun = getPublishTask(event); try { executor.execute(toRun); Result result = toRun.get(TIMEOUT, TimeUnit.SECONDS); String msg = "[" + event.getPlugin() + "] pushed event " + result; switch (result.getStatus()) { case OK: logger.info(msg); break; case ERROR: logger.error(msg); break; } } catch (Exception e) { toRun.cancel(true); logger.error("push failed: timeout reached: " + TIMEOUT + " seconds"); } } }; return publishAndLog; }
From source file:ubic.gemma.core.loader.util.fetcher.AbstractFetcher.java
/** * @param future future task/* w w w .jav a 2 s .co m*/ * @return true if it finished normally, false if it was cancelled. */ protected boolean waitForDownload(FutureTask<Boolean> future) { StopWatch timer = new StopWatch(); timer.start(); long lastTime = timer.getTime(); while (!future.isDone() && !future.isCancelled()) { try { Thread.sleep(AbstractFetcher.INFO_UPDATE_INTERVAL); } catch (InterruptedException ie) { AbstractFetcher.log.info("Cancelling download"); boolean cancelled = future.cancel(true); if (cancelled) { AbstractFetcher.log.info("Download stopped successfully."); return false; } throw new RuntimeException("Cancellation failed."); } if (AbstractFetcher.log.isInfoEnabled() && timer.getTime() > (lastTime + 2000L)) { AbstractFetcher.log.info("Waiting ... " + timer.getTime() + "ms elapsed...."); } } return true; }
From source file:ubic.gemma.loader.util.fetcher.AbstractFetcher.java
/** * @param future//from w w w .ja v a 2 s . c o m * @param expectedSize * @param outputFileName * @return true if it finished normally, false if it was cancelled. */ protected boolean waitForDownload(FutureTask<Boolean> future, long expectedSize, File outputFile) { int iters = 0; long previousSize = 0; StopWatch idleTimer = new StopWatch(); while (!future.isDone() && !future.isCancelled()) { try { Thread.sleep(INFO_UPDATE_INTERVAL); } catch (InterruptedException ie) { log.info("Cancelling download"); boolean cancelled = future.cancel(true); if (cancelled) { return false; } // double check... if (future.isCancelled() || future.isDone()) { return false; } log.error("Cancellation of actual download might not have happend? Task says it was not cancelled: " + future); return false; } /* * Avoid logging too much. If we're waiting for a long download, reduce frequency of updates. */ if (outputFile.length() < expectedSize && (iters < NUMBER_OF_TIMES_TO_LOG_WAITING_BEFORE_REDUCING_VERBOSITY || iters % NUMBER_OF_TIMES_TO_LOG_WAITING_BEFORE_REDUCING_VERBOSITY == 0)) { double percent = 100.00 * outputFile.length() / expectedSize; // can cause npe error, breaking hot deploy if (log != null && log.isInfoEnabled()) { log.info((outputFile.length() + (expectedSize > 0 ? "/" + expectedSize : "") + " bytes read (" + String.format("%.1f", percent) + "%)")); } if (previousSize == outputFile.length()) { /* * Possibly consider bailing after a while. */ if (idleTimer.getTime() > STALLED_BAIL_TIME_LIMIT) { log.warn("Download does not seem to be happening, bailing"); return false; } if (idleTimer.getTime() == 0) idleTimer.start(); } else { idleTimer.reset(); idleTimer.start(); } } if (outputFile.length() >= expectedSize) { // no special action, it will finish soon enough. } previousSize = outputFile.length(); iters++; } if (iters == 0) log.info("File with size " + outputFile.length() + " bytes."); return true; }
From source file:org.apache.kylin.storage.hbase.util.StorageCleanupJob.java
private void cleanUnusedHBaseTables(Configuration conf) throws IOException { CubeManager cubeMgr = CubeManager.getInstance(KylinConfig.getInstanceFromEnv()); // get all kylin hbase tables Connection conn = HBaseConnection.get(KylinConfig.getInstanceFromEnv().getStorageUrl()); Admin hbaseAdmin = conn.getAdmin();/* w w w . ja v a2 s. com*/ String tableNamePrefix = IRealizationConstants.SharedHbaseStorageLocationPrefix; HTableDescriptor[] tableDescriptors = hbaseAdmin.listTables(tableNamePrefix + ".*"); List<String> allTablesNeedToBeDropped = new ArrayList<String>(); for (HTableDescriptor desc : tableDescriptors) { String host = desc.getValue(IRealizationConstants.HTableTag); if (KylinConfig.getInstanceFromEnv().getMetadataUrlPrefix().equalsIgnoreCase(host)) { //only take care htables that belongs to self, and created more than 2 days allTablesNeedToBeDropped.add(desc.getTableName().getNameAsString()); } } // remove every segment htable from drop list for (CubeInstance cube : cubeMgr.listAllCubes()) { for (CubeSegment seg : cube.getSegments()) { String tablename = seg.getStorageLocationIdentifier(); if (allTablesNeedToBeDropped.contains(tablename)) { allTablesNeedToBeDropped.remove(tablename); logger.info("Exclude table " + tablename + " from drop list, as the table belongs to cube " + cube.getName() + " with status " + cube.getStatus()); } } } if (delete == true) { // drop tables ExecutorService executorService = Executors.newSingleThreadExecutor(); for (String htableName : allTablesNeedToBeDropped) { FutureTask futureTask = new FutureTask(new DeleteHTableRunnable(hbaseAdmin, htableName)); executorService.execute(futureTask); try { futureTask.get(deleteTimeout, TimeUnit.MINUTES); } catch (TimeoutException e) { logger.warn("It fails to delete htable " + htableName + ", for it cost more than " + deleteTimeout + " minutes!"); futureTask.cancel(true); } catch (Exception e) { e.printStackTrace(); futureTask.cancel(true); } } executorService.shutdown(); } else { System.out.println("--------------- Tables To Be Dropped ---------------"); for (String htableName : allTablesNeedToBeDropped) { System.out.println(htableName); } System.out.println("----------------------------------------------------"); } hbaseAdmin.close(); }
From source file:org.apache.kylin.tool.StorageCleanupJob.java
private void cleanUnusedHBaseTables(Configuration conf) throws IOException { CubeManager cubeMgr = CubeManager.getInstance(KylinConfig.getInstanceFromEnv()); // get all kylin hbase tables try (HBaseAdmin hbaseAdmin = new HBaseAdmin(conf)) { String tableNamePrefix = IRealizationConstants.SharedHbaseStorageLocationPrefix; HTableDescriptor[] tableDescriptors = hbaseAdmin.listTables(tableNamePrefix + ".*"); List<String> allTablesNeedToBeDropped = new ArrayList<String>(); for (HTableDescriptor desc : tableDescriptors) { String host = desc.getValue(IRealizationConstants.HTableTag); if (KylinConfig.getInstanceFromEnv().getMetadataUrlPrefix().equalsIgnoreCase(host)) { //only take care htables that belongs to self, and created more than 2 days allTablesNeedToBeDropped.add(desc.getTableName().getNameAsString()); }/*from www . j av a2 s. c o m*/ } // remove every segment htable from drop list for (CubeInstance cube : cubeMgr.listAllCubes()) { for (CubeSegment seg : cube.getSegments()) { String tablename = seg.getStorageLocationIdentifier(); if (allTablesNeedToBeDropped.contains(tablename)) { allTablesNeedToBeDropped.remove(tablename); logger.info("Exclude table " + tablename + " from drop list, as the table belongs to cube " + cube.getName() + " with status " + cube.getStatus()); } } } if (delete == true) { // drop tables ExecutorService executorService = Executors.newSingleThreadExecutor(); for (String htableName : allTablesNeedToBeDropped) { FutureTask futureTask = new FutureTask(new DeleteHTableRunnable(hbaseAdmin, htableName)); executorService.execute(futureTask); try { futureTask.get(deleteTimeout, TimeUnit.MINUTES); } catch (TimeoutException e) { logger.warn("It fails to delete htable " + htableName + ", for it cost more than " + deleteTimeout + " minutes!"); futureTask.cancel(true); } catch (Exception e) { e.printStackTrace(); futureTask.cancel(true); } } executorService.shutdown(); } else { System.out.println("--------------- Tables To Be Dropped ---------------"); for (String htableName : allTablesNeedToBeDropped) { System.out.println(htableName); } System.out.println("----------------------------------------------------"); } } }
From source file:ubic.gemma.core.loader.util.fetcher.AbstractFetcher.java
/** * @param future future task//from ww w . j a va 2 s.com * @param expectedSize expected size * @param outputFile output file * @return true if it finished normally, false if it was cancelled. */ protected boolean waitForDownload(FutureTask<Boolean> future, long expectedSize, File outputFile) { int i = 0; long previousSize = 0; StopWatch idleTimer = new StopWatch(); while (!future.isDone() && !future.isCancelled()) { try { Thread.sleep(AbstractFetcher.INFO_UPDATE_INTERVAL); } catch (InterruptedException ie) { if (AbstractFetcher.log != null) { AbstractFetcher.log.info("Cancelling download"); } boolean cancelled = future.cancel(true); if (cancelled) { return false; } // double check... if (future.isCancelled() || future.isDone()) { return false; } if (AbstractFetcher.log != null) { AbstractFetcher.log.error( "Cancellation of actual download might not have happened? Task says it was not cancelled: " + future); } return false; } /* * Avoid logging too much. If we're waiting for a long download, reduce frequency of updates. */ if (outputFile.length() < expectedSize && (i < AbstractFetcher.NUMBER_OF_TIMES_TO_LOG_WAITING_BEFORE_REDUCING_VERBOSITY || i % AbstractFetcher.NUMBER_OF_TIMES_TO_LOG_WAITING_BEFORE_REDUCING_VERBOSITY == 0)) { double percent = 100.00 * outputFile.length() / expectedSize; // can cause npe error, breaking hot deploy if (AbstractFetcher.log != null && AbstractFetcher.log.isInfoEnabled()) { AbstractFetcher.log.info((outputFile.length() + (expectedSize > 0 ? "/" + expectedSize : "") + " bytes read (" + String.format("%.1f", percent) + "%)")); } if (previousSize == outputFile.length()) { /* * Possibly consider bailing after a while. */ if (idleTimer.getTime() > AbstractFetcher.STALLED_BAIL_TIME_LIMIT) { if (AbstractFetcher.log != null) { AbstractFetcher.log.warn("Download does not seem to be happening, bailing"); } return false; } if (idleTimer.getTime() == 0) idleTimer.start(); } else { idleTimer.reset(); idleTimer.start(); } } // if ( outputFile.length() >= expectedSize ) { // // no special action, it will finish soon enough. // } previousSize = outputFile.length(); i++; } if (i == 0) if (AbstractFetcher.log != null) { AbstractFetcher.log.info("File with size " + outputFile.length() + " bytes."); } return true; }
From source file:ubic.basecode.math.linalg.SingularValueDecomposition.java
/** * @param dm/*from w w w . jav a 2 s . c o m*/ */ private void computeSVD(final DoubleMatrix2D dm) { /* * This fails to converge some times, we have to bail. */ FutureTask<cern.colt.matrix.linalg.SingularValueDecomposition> svdFuture = new FutureTask<>( new Callable<cern.colt.matrix.linalg.SingularValueDecomposition>() { @Override public cern.colt.matrix.linalg.SingularValueDecomposition call() { return new cern.colt.matrix.linalg.SingularValueDecomposition(dm); } }); StopWatch timer = new StopWatch(); timer.start(); Executors.newSingleThreadExecutor().execute(svdFuture); while (!svdFuture.isDone() && !svdFuture.isCancelled()) { try { Thread.sleep(100); } catch (InterruptedException ie) { throw new RuntimeException("SVD cancelled"); } if (timer.getTime() > MAX_COMPUTE_TIME) { svdFuture.cancel(true); throw new RuntimeException("SVD failed to converge within " + MAX_COMPUTE_TIME + "ms, bailing"); } } timer.stop(); try { this.svd = svdFuture.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } assert this.svd != null; }
From source file:com.appleframework.monitor.action.LogsAction.java
@RequestMapping(value = "/projects/{projectName}/logs/more", method = RequestMethod.GET) public void console(final HttpServletResponse response, ModelMap map, @PathVariable String projectName, LogQuery logQuery) throws IOException, ParseException { Project project = projectService.findProject(projectName); map.put("project", project); final MongoConverter converter = project.fetchMongoTemplate().getConverter(); final DBCursor cursor = logsService.findLogs(projectName, logQuery); final StringBuffer buf = new StringBuffer(); FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override//from w w w. ja v a2 s. c o m public String call() throws Exception { long startTime = System.currentTimeMillis(); //???20 logger.debug("result:"); while (cursor.hasNext()) { Log log = converter.read(Log.class, cursor.next()); buf.insert(0, log.toString() + "\n"); long current = System.currentTimeMillis(); if ((current - startTime) / 1000 >= mongWaitSeconds) break; } return buf.toString(); } }); executor.execute(task); try { task.get(mongWaitSeconds + 5, TimeUnit.SECONDS); cursor.close(); } catch (Exception e) { logger.error("time out ", e); task.cancel(true); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(buf.toString()); response.getWriter().flush(); }