List of usage examples for java.util.concurrent ExecutorService shutdown
void shutdown();
From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java
/** * Runs given test in a new thread with specified timeout * (DEFAULT_TIMEOUT_IN_SECONDS) and stores the results in given testResult. * /*from w ww . j a v a2s . c o m*/ * @param r * the test to be run * @return the time needed for executing the test */ protected long runWithTimeoutOld(MutationTestRunnable r) { // ArrayList<Thread> threadsPre = ThreadUtil.getThreads(); ExecutorService service = Executors.newSingleThreadExecutor(); Future<?> future = service.submit(r); StopWatch stopWatch = new StopWatch(); stopWatch.start(); service.shutdown(); String exceptionMessage = null; Throwable capturedThrowable = null; try { logger.debug("Start test: "); boolean terminated = service.awaitTermination(timeout, TimeUnit.SECONDS); logger.debug("First timeout"); long time1 = stopWatch.getTime(); if (!terminated) { service.shutdownNow(); } future.get(1, TimeUnit.SECONDS); logger.debug("Second timeout"); long time2 = stopWatch.getTime(); if (time2 - time1 > 1000) { logger.info("Process got some extra time: " + (time2 - time1) + " " + time2); } future.cancel(true); } catch (InterruptedException e) { capturedThrowable = e; } catch (ExecutionException e) { capturedThrowable = e; } catch (TimeoutException e) { exceptionMessage = "Mutation causes test timeout"; capturedThrowable = e; } catch (Throwable t) { capturedThrowable = t; } finally { if (capturedThrowable != null) { if (exceptionMessage == null) { exceptionMessage = "Exception caught during test execution."; } r.setFailed(exceptionMessage, capturedThrowable); } } if (!future.isDone()) { r.setFailed("Mutated Thread is still running after timeout.", null); switchOfMutation(future); } stopWatch.stop(); if (!r.hasFinished()) { shutDown(r, stopWatch); } logger.debug("End timed test, it took " + stopWatch.getTime() + " ms"); return stopWatch.getTime(); }
From source file:com.netsteadfast.greenstep.bsc.command.ScoreCalculationCommand.java
private void processKpisScore(List<VisionVO> visions) throws Exception { //long beg = System.currentTimeMillis(); for (VisionVO vision : visions) { for (PerspectiveVO perspective : vision.getPerspectives()) { for (ObjectiveVO objective : perspective.getObjectives()) { // 2015-04-11 add ExecutorService kpiCalculationPool = Executors .newFixedThreadPool(SimpleUtils.getAvailableProcessors(objective.getKpis().size())); for (KpiVO kpi : objective.getKpis()) { /* 2015-04-11 rem float score = this.calculationMeasureData(kpi); kpi.setScore(score); kpi.setBgColor( BscScoreColorUtils.getBackgroundColor(score) ); kpi.setFontColor( BscScoreColorUtils.getFontColor(score) ); */// w w w. ja va 2 s.co m // 2015-04-11 add ScoreCalculationCallableData data = new ScoreCalculationCallableData(); data.setDefaultMode(true); data.setKpi(kpi); data = kpiCalculationPool.submit(new ScoreCalculationCallable(data)).get(); } kpiCalculationPool.shutdown(); } } } //long end = System.currentTimeMillis(); //System.out.println( this.getClass().getName() + " use time(MS) = " + (end-beg) ); }
From source file:de.undercouch.citeproc.TestSuiteRunner.java
/** * Runs tests/* w w w . j a v a2 s .com*/ * @param f either a compiled test file (.json) to run or a directory * containing compiled test files * @param runnerType the type of the script runner that will be used * to execute all JavaScript code * @throws IOException if a file could not be loaded */ public void runTests(File f, RunnerType runnerType) throws IOException { ScriptRunnerFactory.setRunnerType(runnerType); { ScriptRunner sr = ScriptRunnerFactory.createRunner(); System.out.println("Using script runner: " + sr.getName() + " " + sr.getVersion()); } //find test files File[] testFiles; if (f.isDirectory()) { testFiles = f.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".json"); } }); } else { testFiles = new File[] { f }; } AnsiConsole.systemInstall(); try { long start = System.currentTimeMillis(); int count = testFiles.length; int success = 0; ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); //submit a job for each test file List<Future<Boolean>> fus = new ArrayList<Future<Boolean>>(); for (File fi : testFiles) { fus.add(executor.submit(new TestCallable(fi))); } //receive results try { for (Future<Boolean> fu : fus) { if (fu.get()) { ++success; } } } catch (Exception e) { //should never happen throw new RuntimeException(e); } executor.shutdown(); //output total time long end = System.currentTimeMillis(); double time = (end - start) / 1000.0; System.out.println("Successfully executed " + success + " of " + count + " tests."); System.out.println(String.format(Locale.ENGLISH, "Total time: %.3f secs", time)); } finally { AnsiConsole.systemUninstall(); } }
From source file:org.apache.solr.client.solrj.impl.HttpSolrClient.java
/** * @lucene.experimental/*from ww w . ja va2 s. c o m*/ */ public HttpUriRequestResponse httpUriRequest(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpUriRequestResponse mrr = new HttpUriRequestResponse(); final HttpRequestBase method = createMethod(request, null); ExecutorService pool = ExecutorUtil.newMDCAwareFixedThreadPool(1, new SolrjNamedThreadFactory("httpUriRequest")); try { MDC.put("HttpSolrClient.url", baseUrl); mrr.future = pool.submit(() -> executeMethod(method, processor)); } finally { pool.shutdown(); MDC.remove("HttpSolrClient.url"); } assert method != null; mrr.httpUriRequest = method; return mrr; }
From source file:com.netflix.priam.resources.BackupServlet.java
/** * Convert SSTable2Json and search for given key */// ww w. j a v a 2 s .co m public void checkSSTablesForKey(String rowkey, String keyspace, String cf, String fileExtension, String jsonFilePath) throws Exception { try { logger.info("Starting SSTable2Json conversion ..."); //Setting timeout to 10 Mins long TIMEOUT_PERIOD = 10l; String unixCmd = formulateCommandToRun(rowkey, keyspace, cf, fileExtension, jsonFilePath); String[] cmd = { "/bin/sh", "-c", unixCmd.toString() }; final Process p = Runtime.getRuntime().exec(cmd); Callable<Integer> callable = new Callable<Integer>() { @Override public Integer call() throws Exception { int returnCode = p.waitFor(); return returnCode; } }; ExecutorService exeService = Executors.newSingleThreadExecutor(); try { Future<Integer> future = exeService.submit(callable); int returnVal = future.get(TIMEOUT_PERIOD, TimeUnit.MINUTES); if (returnVal == 0) logger.info("Finished SSTable2Json conversion and search."); else logger.error("Error occurred during SSTable2Json conversion and search."); } catch (TimeoutException e) { logger.error(ExceptionUtils.getFullStackTrace(e)); throw e; } finally { p.destroy(); exeService.shutdown(); } } catch (IOException e) { logger.error(ExceptionUtils.getFullStackTrace(e)); } }
From source file:com.taobao.android.tpatch.utils.SmaliUtils.java
/** * dex?smali/*from w ww. j ava 2 s .co 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; }
From source file:com.clonescriptscrapper.crawler.CloneScriptScrapper.java
public void crawledCategories() throws URISyntaxException, IOException, InterruptedException, Exception { String url = "http://www.clonescriptdirectory.com/"; // Document doc = Jsoup.parse(fetchPage(new URI(url))); String response = ""; response = new GetRequestHandler().doGetRequest(new URL(url)); Document doc = Jsoup.parse(response); // System.out.println("---" + doc); Elements ele = doc.select("table[class=categories] tbody tr td a"); for (Element ele1 : ele) { objCategories = new Categories(); String title = ele1.text(); String href = ele1.attr("href"); System.out.println("Title : " + ele1.text()); System.out.println("Href : " + ele1.attr("href")); objCategories.setCategoryName(title); objCategories.setCategoryUrl(href); objCloneScriptDirectoryDaoImpl.insertCategoriesData(objCategories); }/*from w w w. j ava 2 s . c o m*/ List<Future<String>> list = new ArrayList<Future<String>>(); ExecutorService executor = Executors.newFixedThreadPool(5); List<Categories> listCatogories = objCloneScriptDirectoryDaoImpl.getCategoriesDataList(); for (Categories listCatogory : listCatogories) { try { objCloneScriptDirectoryDaoImpl.updateCategoriesData(objCategories); Callable worker = new CrawlingEachUrlData(listCatogory, objCloneScriptDirectoryDaoImpl); Future<String> future = executor.submit(worker); list.add(future); } catch (Exception exx) { System.out.println(exx); } } for (Future<String> fut : list) { try { //print the return value of Future, notice the output delay in console // because Future.get() waits for task to get completed System.out.println(new Date() + "::" + fut.get()); } catch (InterruptedException | ExecutionException ep) { ep.printStackTrace(); } } //shut down the executor service now executor.shutdown(); // objcrawlingUrlData.crawlingUrlData(href); }
From source file:com.microsoft.azure.servicebus.samples.timetolive.TimeToLive.java
public void run(String connectionString) throws Exception { IMessageSender sendClient;/* w w w . j av a2s .c o m*/ CompletableFuture<Void> receiveTask; CompletableFuture<Void> fixUpTask; // send messages sendClient = ClientFactory.createMessageSenderFromConnectionStringBuilder( new ConnectionStringBuilder(connectionString, "BasicQueue")); this.sendMessagesAsync(sendClient); // wait for all messages to expire Thread.sleep(15 * 1000); ExecutorService executorService = Executors.newCachedThreadPool(); // start the receiver tasks and the fixup tasks receiveTask = this.receiveMessagesAsync(connectionString, "BasicQueue", executorService); fixUpTask = this.pickUpAndFixDeadLetters(connectionString, "BasicQueue", sendClient, executorService); // wait for ENTER or 10 seconds elapsing waitForEnter(10); // cancel the running tasks receiveTask.cancel(true); fixUpTask.cancel(true); // wait for the tasks to complete CompletableFuture.allOf(sendClient.closeAsync(), receiveTask.exceptionally(t -> { if (t instanceof CancellationException) { return null; } throw new RuntimeException(t); }), fixUpTask.exceptionally(t -> { if (t instanceof CancellationException) { return null; } throw new RuntimeException(t); })).join(); executorService.shutdown(); }
From source file:org.suren.autotest.web.framework.selenium.action.SeleniumFileUpload.java
@Override public boolean upload(Element element, final File file) { WebElement webEle = findElement(element); if (webEle != null) { logger.info("File upload, element is already found."); ExecutorService executor = Executors.newSingleThreadExecutor(); final AutoItCmd autoItCmd = new AutoItCmd(); try {//from www .j a v a2 s .co m Future<?> future = executor.submit(new Runnable() { @Override public void run() { try { autoItCmd.execFileChoose(file); } catch (Exception e) { e.printStackTrace(); } } }); synchronized (autoItCmd) { autoItCmd.wait(); } click(element); if (!future.isDone()) { future.get(30, TimeUnit.SECONDS); } return true; } catch (InterruptedException | ExecutionException | TimeoutException e) { logger.error("File uplod error.", e); e.printStackTrace(); } finally { autoItCmd.close(); executor.shutdown(); } } else { logger.error("Can not found element, when prepare to upload file."); } return false; }
From source file:me.carpela.network.pt.cracker.tools.ttorrent.Torrent.java
private static String hashFiles(List<File> files, int pieceLenght) throws InterruptedException, IOException, NoSuchAlgorithmException { int threads = getHashingThreadsCount(); ExecutorService executor = Executors.newFixedThreadPool(threads); ByteBuffer buffer = ByteBuffer.allocate(pieceLenght); 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) { length += file.length();/*from www. 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) { 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 / pieceLenght)); return hashes.toString(); }