List of usage examples for java.util.concurrent ScheduledExecutorService shutdown
void shutdown();
From source file:com.ilscipio.scipio.common.FileListener.java
/** * Start a file listener (WatchService) and run a service of a given name and writes the result to the database * Can be used to implements EECAs to auto-update information based on file changes **///from ww w . j av a 2 s . co m public static void startFileListener(String name, String location) { try { if (UtilValidate.isNotEmpty(name) && UtilValidate.isNotEmpty(location)) { if (getThreadByName(name) != null) { Debug.logInfo("Filelistener " + name + " already started. Skipping...", module); } else { URL resLocation = UtilURL.fromResource(location); Path folderLocation = Paths.get(resLocation.toURI()); if (folderLocation == null) { throw new UnsupportedOperationException("Directory not found"); } final WatchService folderWatcher = folderLocation.getFileSystem().newWatchService(); // register all subfolders Files.walkFileTree(folderLocation, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { dir.register(folderWatcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); return FileVisitResult.CONTINUE; } }); // start the file watcher thread below ScipioWatchQueueReader fileListener = new ScipioWatchQueueReader(folderWatcher, name, location); ScheduledExecutorService executor = ExecutionPool.getScheduledExecutor( FILE_LISTENER_THREAD_GROUP, "filelistener-startup", Runtime.getRuntime().availableProcessors(), 0, true); try { executor.submit(fileListener, name); } finally { executor.shutdown(); } Debug.logInfo("Starting FileListener thread for " + name, module); } } } catch (Exception e) { Debug.logError("Could not start FileListener " + name + " for " + location + "\n" + e, module); } }
From source file:com.github.joshelser.dropwizard.metrics.hadoop.StandaloneExample.java
/** * Runs a number of threads which generate metrics. *///from ww w . j a va 2 s .c om public static void generateMetrics(final MetricRegistry metrics, final long metricsToGenerate, final int period, final TimeUnit periodTimeUnit, HadoopMetrics2Reporter metrics2Reporter, int numThreads) throws Exception { final ScheduledExecutorService pool = Executors.newScheduledThreadPool(numThreads); final CountDownLatch latch = new CountDownLatch(numThreads); for (int i = 0; i < numThreads; i++) { final int id = i; final int halfPeriod = (period / 2); Runnable task = new Runnable() { private long executions = 0; final Random r = new Random(); @Override public void run() { if (executions >= metricsToGenerate) { return; } metrics.counter("foo counter thread" + id).inc(); executions++; if (executions < metricsToGenerate) { pool.schedule(this, period + r.nextInt(halfPeriod), periodTimeUnit); } else { latch.countDown(); } } }; pool.schedule(task, period, periodTimeUnit); } while (!latch.await(2, TimeUnit.SECONDS)) { metrics2Reporter.printQueueDebugMessage(); } pool.shutdown(); pool.awaitTermination(5000, TimeUnit.SECONDS); }
From source file:org.dcm4che3.tool.syslog.Syslog.java
public void close() { auditLogger.closeActiveConnection(); ScheduledExecutorService scheduler = logDevice.getScheduledExecutor(); if (scheduler != null) scheduler.shutdown(); }
From source file:com.ah.be.license.AeroLicenseTimer.java
/** * Stop your defined license timer./*from w w w . jav a 2 s . c o m*/ * * @param arg_Timer - * @param arg_Future - * @return String : the error message */ public static String stopLicenseTimer(ScheduledExecutorService arg_Timer, ScheduledFuture<?> arg_Future) { try { if (!arg_Timer.isShutdown()) { if (null != arg_Future) { arg_Future.cancel(false); } // Disable new tasks from being submitted. arg_Timer.shutdown(); try { // Wait a while for existing tasks to terminate. if (!arg_Timer.awaitTermination(5, TimeUnit.SECONDS)) { // Cancel currently executing tasks. arg_Timer.shutdownNow(); // Wait a while for tasks to respond to being canceled. if (!arg_Timer.awaitTermination(5, TimeUnit.SECONDS)) { return "The license timer does not terminate."; } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted. //arg_Timer.shutdownNow(); } } } catch (Exception e) { return "There is something wrong with timer stop."; } return null; }
From source file:net.sourceforge.fullsync.cli.Main.java
public static void startup(String[] args, Launcher launcher) throws Exception { initOptions();// w w w . j a v a2s . c o m String configDir = getConfigDir(); CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException ex) { System.err.println(ex.getMessage()); printHelp(); System.exit(1); } if (line.hasOption('V')) { System.out.println(String.format("FullSync version %s", Util.getFullSyncVersion())); //$NON-NLS-1$ System.exit(0); } // Apply modifying options if (!line.hasOption("v")) { //$NON-NLS-1$ System.setErr(new PrintStream(new FileOutputStream(getLogFileName()))); } if (line.hasOption("h")) { //$NON-NLS-1$ printHelp(); System.exit(0); } upgradeLegacyPreferencesLocation(configDir); String profilesFile; if (line.hasOption("P")) { //$NON-NLS-1$ profilesFile = line.getOptionValue("P"); //$NON-NLS-1$ } else { profilesFile = configDir + FullSync.PROFILES_XML; upgradeLegacyProfilesXmlLocation(profilesFile); } final String prefrencesFile = configDir + FullSync.PREFERENCES_PROPERTIES; final Injector injector = Guice.createInjector(new FullSyncModule(line, prefrencesFile)); final RuntimeConfiguration rtConfig = injector.getInstance(RuntimeConfiguration.class); injector.getInstance(ProfileManager.class).setProfilesFileName(profilesFile); final ScheduledExecutorService scheduledExecutorService = injector .getInstance(ScheduledExecutorService.class); final EventListener deadEventListener = new EventListener() { private final Logger logger = LoggerFactory.getLogger("DeadEventLogger"); //$NON-NLS-1$ @Subscribe private void onDeadEvent(DeadEvent deadEvent) { if (!(deadEvent.getEvent() instanceof ShutdownEvent)) { logger.warn("Dead event triggered: {}", deadEvent); //$NON-NLS-1$ } } }; final EventBus eventBus = injector.getInstance(EventBus.class); eventBus.register(deadEventListener); final Semaphore sem = new Semaphore(0); Runtime.getRuntime().addShutdownHook(new Thread(() -> { Logger logger = LoggerFactory.getLogger(Main.class); logger.debug("shutdown hook called, starting orderly shutdown"); //$NON-NLS-1$ eventBus.post(new ShutdownEvent()); scheduledExecutorService.shutdown(); try { scheduledExecutorService.awaitTermination(5, TimeUnit.MINUTES); } catch (InterruptedException e) { // not relevant } logger.debug("shutdown hook finished, releaseing main thread semaphore"); //$NON-NLS-1$ sem.release(); })); if (rtConfig.isDaemon().orElse(false).booleanValue() || rtConfig.getProfileToRun().isPresent()) { finishStartup(injector); sem.acquireUninterruptibly(); System.exit(0); } else { launcher.launchGui(injector); System.exit(0); } }
From source file:com.networknt.client.oauth.OauthHelper.java
/** * renew the given Jwt jwt asynchronously. * When fail, it will swallow the exception, so no need return type to be handled by caller. * @param jwt the jwt you want to renew/* w w w .ja v a2 s . c om*/ */ private static void renewCCTokenAsync(final Jwt jwt) { // Not expired yet, try to renew async but let requests use the old token. logger.trace("In renew window but token is not expired yet."); if (!jwt.isRenewing() || System.currentTimeMillis() > jwt.getEarlyRetryTimeout()) { jwt.setRenewing(true); jwt.setEarlyRetryTimeout(System.currentTimeMillis() + jwt.getEarlyRefreshRetryDelay()); logger.trace("Retrieve token async is called while token is not expired yet"); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); executor.schedule(() -> { Result<Jwt> result = getCCTokenRemotely(jwt); if (result.isFailure()) { // swallow the exception here as it is on a best effort basis. logger.error("Async retrieve token error with status: {}", result.getError().toString()); } //set renewing flag to false after response, doesn't matter if it's success or fail. jwt.setRenewing(false); }, 50, TimeUnit.MILLISECONDS); executor.shutdown(); } }
From source file:org.apache.flink.runtime.filecache.FileCache.java
/** * Shuts down the file cache by cancelling all *//* www . j a v a2 s . c o m*/ public void shutdown() { synchronized (lock) { // first shutdown the thread pool ScheduledExecutorService es = this.executorService; if (es != null) { es.shutdown(); try { es.awaitTermination(5000L, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // may happen } } entries.clear(); // clean up the all storage directories for (File dir : storageDirectories) { try { FileUtils.deleteDirectory(dir); } catch (IOException e) { LOG.error("File cache could not properly clean up storage directory."); } } // Remove shutdown hook to prevent resource leaks, unless this is invoked by the // shutdown hook itself if (shutdownHook != null && shutdownHook != Thread.currentThread()) { try { Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (IllegalStateException e) { // race, JVM is in shutdown already, we can safely ignore this } catch (Throwable t) { LOG.warn("Exception while unregistering file cache's cleanup shutdown hook."); } } } }
From source file:com.all.download.manager.ScheduledExecutorServiceSingleton.java
public void destroy() { Iterator<ScheduledExecutorService> iterator = scheduledExecutorServiceList.iterator(); while (iterator.hasNext()) { ScheduledExecutorService scheduledExecutorService = iterator.next(); try {/* w ww . j a v a 2s .c o m*/ // close the thread pool, should only be closed here but no harm if // it was closed somewhere else scheduledExecutorService.shutdown(); if (!scheduledExecutorService.awaitTermination(5, TimeUnit.SECONDS)) { log.warn("Thread pool did not terminate correctly"); } } catch (InterruptedException ie) { scheduledExecutorService.shutdownNow(); } iterator.remove(); } }
From source file:io.fabric8.che.starter.openshift.CheDeploymentConfig.java
private void waitUntilDeploymentConfigIsAvailable(final OpenShiftClient client, String namespace) { final BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1); final Runnable readinessPoller = new Runnable() { public void run() { try { if (isDeploymentAvailable(client, namespace)) { queue.put(true);//from w w w. j av a 2s . c o m return; } else { queue.put(false); return; } } catch (Throwable t) { try { if (queue.isEmpty()) { queue.put(false); } return; } catch (InterruptedException e) { } } } }; ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture<?> poller = executor.scheduleWithFixedDelay(readinessPoller, 0, 500, TimeUnit.MILLISECONDS); executor.schedule(new Runnable() { @Override public void run() { poller.cancel(true); } }, Integer.valueOf(startTimeout), TimeUnit.SECONDS); try { while (!waitUntilReady(queue)) { } } finally { if (!poller.isDone()) { poller.cancel(true); } executor.shutdown(); } }
From source file:com.hurence.logisland.connect.opc.da.OpcDaSourceConnectorTest.java
@Test @Ignore//w ww .ja va2s.c om public void e2eTest() throws Exception { OpcDaSourceConnector connector = new OpcDaSourceConnector(); Map<String, String> properties = new HashMap<>(); properties.put(OpcDaSourceConnector.PROPERTY_AUTH_NTLM_DOMAIN, "OPC-9167C0D9342"); properties.put(CommonDefinitions.PROPERTY_CONNECTION_SOCKET_TIMEOUT, "2000"); properties.put(OpcDaSourceConnector.PROPERTY_AUTH_NTLM_PASSWORD, "opc"); properties.put(OpcDaSourceConnector.PROPERTY_AUTH_NTLM_USER, "OPC"); properties.put(CommonDefinitions.PROPERTY_SERVER_URI, "opc.da://192.168.99.100"); properties.put(OpcDaSourceConnector.PROPERTY_SERVER_CLSID, "F8582CF2-88FB-11D0-B850-00C0F0104305"); properties.put(CommonDefinitions.PROPERTY_TAGS_ID, "Random.Real8,Triangle Waves.Int4"); properties.put(CommonDefinitions.PROPERTY_TAGS_STREAM_MODE, "SUBSCRIBE,POLL"); properties.put(CommonDefinitions.PROPERTY_TAGS_SAMPLING_RATE, "PT3S,PT1S"); properties.put(OpcDaSourceConnector.PROPERTY_SESSION_REFRESH_PERIOD, "1000"); properties.put(OpcDaSourceConnector.PROPERTY_TAGS_DATA_TYPE_OVERRIDE, "0,8"); connector.start(properties); OpcDaSourceTask task = new OpcDaSourceTask(); task.start(connector.taskConfigs(1).get(0)); ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor(); Gson json = new Gson(); es.scheduleAtFixedRate(() -> { try { task.poll().stream() .map(a -> org.apache.commons.lang3.tuple.Pair.of( new Date((Long) a.sourceOffset().get(OpcRecordFields.SAMPLED_TIMESTAMP)), json.toJson(a))) .forEach(System.out::println); } catch (InterruptedException e) { //do nothing } }, 0, 10, TimeUnit.MILLISECONDS); Thread.sleep(600000); task.stop(); es.shutdown(); connector.stop(); }