List of usage examples for java.util.concurrent ExecutorService awaitTermination
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
From source file:password.pwm.util.java.JavaHelper.java
public static boolean closeAndWaitExecutor(final ExecutorService executor, final TimeDuration timeDuration) { if (executor == null) { return true; }/*from w w w . j a v a 2 s. c om*/ executor.shutdown(); try { return executor.awaitTermination(timeDuration.getTotalMilliseconds(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOGGER.warn("unexpected error shutting down executor service " + executor.getClass().toString() + " error: " + e.getMessage()); } return false; }
From source file:Main.java
public static boolean stop(ExecutorService executorService, int waitBeforeTerminateSecs, Logger logger) /* */ {//from w w w . j a va 2 s . co m /* 53 */int waitMillis = Math.max(1000, 1000 * waitBeforeTerminateSecs); /* */ /* */ /* 56 */executorService.shutdown(); /* */ /* */ /* 59 */boolean stopped = false; /* 60 */while ((waitMillis > 0) && (!stopped)) { /* 61 */long startMillis = System.currentTimeMillis(); /* */try { /* 63 */logger.debug("Waiting for thread pool to stop"); /* 64 */stopped = executorService.awaitTermination(waitMillis, TimeUnit.MILLISECONDS); /* */} catch (InterruptedException e) { /* 66 */logger.debug("Thread was interrupted while it was waiting for thread pool to stop", e); /* 67 */Thread.currentThread().interrupt(); /* 68 */break; /* */} /* 70 */waitMillis = (int) (waitMillis - (System.currentTimeMillis() - startMillis)); /* */} /* */ /* 73 */if (!executorService.isTerminated()) { /* 74 */logger.warn("Thread pool will be forcibly stopped now if it has not already stopped"); /* 75 */executorService.shutdownNow(); /* */try { /* 77 */stopped = executorService.awaitTermination(waitBeforeTerminateSecs, TimeUnit.SECONDS); /* */} /* */catch (InterruptedException e) { } /* */ /* 81 */if (!executorService.isTerminated()) { /* 82 */logger.warn("Could not shutdown thread pool in [{}] seconds", Integer.valueOf(waitBeforeTerminateSecs)); /* */} /* */} /* */ /* 86 */return stopped; /* */}
From source file:org.apache.sentry.api.common.SentryServiceUtil.java
/** * Gracefully shut down an Executor service. * <p>/*from w ww .j a v a 2s .c o m*/ * This code is based on the Javadoc example for the Executor service. * <p> * First call shutdown to reject incoming tasks, and then call * shutdownNow, if necessary, to cancel any lingering tasks. * * @param pool the executor service to shut down * @param poolName the name of the executor service to shut down to make it easy for debugging * @param timeout the timeout interval to wait for its termination * @param unit the unit of the timeout * @param logger the logger to log the error message if it cannot terminate. It could be null */ public static void shutdownAndAwaitTermination(ExecutorService pool, String poolName, long timeout, TimeUnit unit, Logger logger) { Preconditions.checkNotNull(pool); pool.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!pool.awaitTermination(timeout, unit)) { pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if ((!pool.awaitTermination(timeout, unit)) && (logger != null)) { logger.error("Executor service {} did not terminate", StringUtils.defaultIfBlank(poolName, "null")); } } } catch (InterruptedException ignored) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } }
From source file:org.apache.vxquery.xtest.util.DiskPerformance.java
static <T> void runThreadTest(Class<T> testType, DiskPerformance dp, int threads, int bufferSize) throws InstantiationException, IllegalAccessException { ExecutorService es = Executors.newCachedThreadPool(); ArrayList<IDiskTest> threadTests = new ArrayList<IDiskTest>(); for (int i = 0; i < threads; ++i) { threadTests.add((IDiskTest) testType.newInstance()); }/*from ww w .j a va 2 s . c o m*/ for (IDiskTest test : threadTests) { test.setFile(dp.getNextFile()); test.setBufferSize(bufferSize); test.setParser(dp.getNewParser().first); es.execute((Runnable) test); } es.shutdown(); try { es.awaitTermination(60, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } // System.out.println("Completed thread batch: " + new Date()); }
From source file:com.uniteddev.Unity.Downloader.java
public static void removeRedundancies() throws InterruptedException { class removeRedundancy implements Runnable { private int i; removeRedundancy(int i) { this.i = i; }// w w w .j av a 2 s .c om public void run() { files.remove(this.i); } } int i = 0; ExecutorService pool = Executors.newFixedThreadPool(cores); while (i < files.size()) { String file = files.get(i); file = namefix(file); if (new File(Minecraft.getWorkingDirectory(), file).exists()) pool.submit(new removeRedundancy(i)); // this was originally a while loop else i++; } pool.shutdown(); pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); }
From source file:org.semarglproject.rdf.rdfa.TestSuiteDownloadHelper.java
public static void downloadAll(int parallelism) throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(parallelism); executorService.execute(new TestDownloadWorker("rdfa1.0", "xhtml1")); executorService.execute(new TestDownloadWorker("rdfa1.0", "svg")); executorService.execute(new TestDownloadWorker("rdfa1.0", "xml")); executorService.execute(new TestDownloadWorker("rdfa1.1", "html4")); executorService.execute(new TestDownloadWorker("rdfa1.1", "xhtml1")); executorService.execute(new TestDownloadWorker("rdfa1.1", "html5")); executorService.execute(new TestDownloadWorker("rdfa1.1", "xml")); executorService.execute(new TestDownloadWorker("rdfa1.1", "svg")); executorService.shutdown();/*from w w w.j ava2 s.c om*/ executorService.awaitTermination(10, TimeUnit.MINUTES); }
From source file:com.dsclab.loader.app.Loader.java
public static void load(Configs prop) throws SQLException, ClassNotFoundException, InterruptedException, ExecutionException { int readThread = prop.getReadThread(); int writeThread = prop.getWriteThread(); ExecutorService readExecutor = Executors.newFixedThreadPool(readThread); ExecutorService writeExecutor = Executors.newFixedThreadPool(writeThread); LOG.info("Start load: writeThread:" + writeThread + ", readThread:" + readThread); BlockingQueue<List<String>> contentQueue = new LinkedBlockingQueue<>(); int tableCount = tableTask.size(); int sum = 0;//from w w w . j ava2s . c o m for (int i = 0; i < tableCount; i++) { sum = sum + tableTask.get(i).getTaskSqlList().size(); } for (int i = 0; i < sum; i++) { readExecutor.submit(new ProducerThread(prop.getInputURL(), contentQueue)); writeExecutor.submit(new ConsumerThread(prop.getOutputURL(), contentQueue)); } readExecutor.shutdown(); readExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println("[CHIA7712] read threads end"); writeExecutor.shutdown(); writeExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println("[CHIA7712] write threads end"); }
From source file:org.jactr.core.concurrent.ExecutorServices.java
/** * shutdown and wait for the shutdown of all the executors that are currently * installed. if millisecondsToWait is 0, it will wait indefinitely */// w ww. j ava 2 s. c o m static public void shutdown(long millisecondsToWait) { synchronized (_executors) { _isShuttingDown = true; } Collection<String> executorNames = new ArrayList<String>(); getExecutorNames(executorNames); /* * issue shutdown */ for (String name : executorNames) { ExecutorService executor = getExecutor(name); if (executor != null && !executor.isShutdown()) executor.shutdown(); } /* * and wait */ long interval = 500; long abortAt = System.currentTimeMillis() + millisecondsToWait; if (millisecondsToWait == 0) abortAt = Long.MAX_VALUE; while (abortAt > System.currentTimeMillis() && executorNames.size() != 0) { for (String name : executorNames) { ExecutorService executor = getExecutor(name); if (executor != null) try { if (executor.awaitTermination(interval, TimeUnit.MILLISECONDS)) removeExecutor(name); else if (LOGGER.isDebugEnabled()) LOGGER.debug(name + " did not terminate after " + interval + "ms"); } catch (Exception e) { if (LOGGER.isWarnEnabled()) LOGGER.warn("Failed to terminate " + name, e); removeExecutor(name); } } /* * get the current names again.. */ executorNames.clear(); getExecutorNames(executorNames); } if (executorNames.size() != 0) { if (LOGGER.isWarnEnabled()) LOGGER.warn("Forcing unresponsive executors to terminate " + executorNames + " after " + millisecondsToWait + "ms"); for (String name : executorNames) { ExecutorService executor = getExecutor(name); if (executor != null) executor.shutdownNow(); } } synchronized (_executors) { _executors.clear(); _isShuttingDown = false; } }
From source file:edu.stanford.epad.epadws.queries.Dcm4CheeQueries.java
public static DICOMElementList getDICOMElementsFromWADO(String studyUID, String seriesUID, String imageUID, SegmentedProperty catTypeProp) { String catCode = ""; String typeCode = ""; DICOMElementList dicomElementList = new DICOMElementList(); DICOMElementList dicomElementListNoSkip = new DICOMElementList(); boolean skipThumbnail = false; try {//w w w . j a v a2 s. c om File temporaryDICOMFile = File.createTempFile(imageUID, ".tmp"); int wadoStatusCode = DCM4CHEEUtil.downloadDICOMFileFromWADO(studyUID, seriesUID, imageUID, temporaryDICOMFile); if (wadoStatusCode == HttpServletResponse.SC_OK) { File tempTag = File.createTempFile(imageUID, "_tag.tmp"); ExecutorService taskExecutor = Executors.newFixedThreadPool(4); taskExecutor.execute(new DicomHeadersTask(seriesUID, temporaryDICOMFile, tempTag)); taskExecutor.shutdown(); try { taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); BufferedReader tagReader = null; try { String dicomElementString; FileReader tagFileReader = new FileReader(tempTag.getAbsolutePath()); tagReader = new BufferedReader(tagFileReader); skipThumbnail = false; String currentSequence = ""; while ((dicomElementString = tagReader.readLine()) != null) { if (dicomElementString.contains("(0009,1110)")) // hard code for now TODO:??? skipThumbnail = true; if (dicomElementString.contains("(FFFE,E0DD)")) skipThumbnail = false; int sequence = dicomElementString.indexOf("SQ #-1"); if (sequence != -1) currentSequence = dicomElementString.substring(sequence + 7); if (dicomElementString.contains("Sequence Delimitation Item")) currentSequence = ""; DICOMElement dicomElement = decodeDICOMElementString(dicomElementString); DICOMElement dicomElementNoSkip = decodeDICOMElementString(dicomElementString); if (dicomElement != null) { if (!skipThumbnail) { dicomElement.parentSequenceName = currentSequence; dicomElementList.addDICOMElement(dicomElement); if (dicomElementString.contains("(0008,0100)")) { if (dicomElement.parentSequenceName != null && dicomElement.parentSequenceName.equalsIgnoreCase( "Segmented Property Category Code Sequence"))//category code { catCode = dicomElement.value.trim(); log.info("cat code is " + catCode); } else if (dicomElement.parentSequenceName != null && dicomElement.parentSequenceName .equalsIgnoreCase("Segmented Property Type Code Sequence"))//category code { typeCode = dicomElement.value.trim(); log.info("type code is " + typeCode); } } } //make a list with all the skip items //at the end if the skip is not closed then use this list else { log.warning("Warning: skip sequence. skipping " + dicomElementString); dicomElementNoSkip.parentSequenceName = currentSequence; dicomElementListNoSkip.addDICOMElement(dicomElementNoSkip); } } else { //too much log // log.warning("Warning: could not decode DICOM element " + dicomElementString + ""); } } } finally { IOUtils.closeQuietly(tagReader); try { temporaryDICOMFile.delete(); tempTag.delete(); } catch (Exception x) { } ; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warning("DICOM headers task for series " + seriesUID + " interrupted!"); } } else { log.warning("Error invoking dcm4chee to get DICOM headers for series " + seriesUID + "; status code=" + wadoStatusCode); } } catch (IOException e) { log.warning("IOException retrieving DICOM headers for image " + imageUID + " in series " + seriesUID, e); } try { if (catTypeProp != null && !catCode.equals("") && !typeCode.equals("")) { SegmentedPropertyHelper helper = new SegmentedPropertyHelper(); SegmentedProperty prop = helper.getProperty(catCode, typeCode); if (prop != null) { catTypeProp.copyValuesFrom(prop); } else { log.info("Category-type pair not found"); } } } catch (Exception ex) { log.warning("Exception in getting category type ", ex); } if (skipThumbnail) { log.warning("End of skip not found returning noskip data. "); return dicomElementListNoSkip; } return dicomElementList; }
From source file:org.semarglproject.rdf.rdfa.RdfaTestBundle.java
public static void downloadAllTests(int parallelism) throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(parallelism); executorService.execute(new TestDownloadWorker("rdfa1.0", "xhtml1")); executorService.execute(new TestDownloadWorker("rdfa1.0", "svg")); executorService.execute(new TestDownloadWorker("rdfa1.1", "html4")); executorService.execute(new TestDownloadWorker("rdfa1.1", "xhtml1")); executorService.execute(new TestDownloadWorker("rdfa1.1", "html5")); executorService.execute(new TestDownloadWorker("rdfa1.1", "xml")); executorService.execute(new TestDownloadWorker("rdfa1.1", "svg")); executorService.shutdown();//from w w w .j av a2 s . c o m executorService.awaitTermination(10, TimeUnit.MINUTES); }