List of usage examples for java.lang Runtime addShutdownHook
public void addShutdownHook(Thread hook)
From source file:Message.java
public static void main(String[] args) { try {// w w w. ja va2 s .c om // register Message as shutdown hook Runtime runTime = Runtime.getRuntime(); runTime.addShutdownHook(new Message()); } catch (Exception e) { e.printStackTrace(); } }
From source file:Message.java
public static void main(String[] args) { try {/* w w w . j a v a 2 s . co m*/ Message p = new Message(); // register Message as shutdown hook Runtime runTime = Runtime.getRuntime(); runTime.addShutdownHook(p); // remove the hook runTime.removeShutdownHook(p); System.out.println("Program is closing..."); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] arg) { Runtime runTime = Runtime.getRuntime(); Main hook = new Main(); runTime.addShutdownHook(new Thread(hook)); }
From source file:com.ok2c.lightmtp.examples.LocalMailServerTransportExample.java
public static void main(final String[] args) throws Exception { File workingDir = new File("."); IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build(); final MailServerTransport mta = new LocalMailServerTransport(workingDir, config); InetSocketAddress sockaddress = new InetSocketAddress("localhost", 2525); InetAddressRange iprange = new InetAddressRange(InetAddress.getByName("127.0.0.0"), 8); mta.start(new DefaultIdGenerator(), new MyRemoteAddressValidator(iprange), new MyEnvelopValidator(), new MyDeliveryHandler()); mta.listen(sockaddress);//w w w. j av a 2 s .c om System.out.println("LMTP server listening on " + sockaddress); Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(new Thread() { @Override public void run() { try { mta.shutdown(); } catch (IOException ex) { mta.forceShutdown(); } } }); }
From source file:com.apporiented.hermesftp.FtpServerApp.java
/** * Add shutdown hook.// w w w .j ava 2 s . c o m */ private static void addShutdownHook(final List<FtpServer> servers) { Runnable shutdownHook = new Runnable() { public void run() { for (FtpServer ftpServer : servers) { log.info("Stopping server '" + ftpServer.getName() + "'."); ftpServer.abort(); } log.info("All servers down."); } }; Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(new Thread(shutdownHook)); }
From source file:com.acmutv.ontoqa.tool.runtime.RuntimeManager.java
/** * Registers atexit runnables as JVM shutdown hooks. * @param hooks atexit runnables.//from w w w . ja v a 2s.com * @see Runtime */ public static void registerShutdownHooks(Runnable... hooks) { Runtime runtime = Runtime.getRuntime(); for (Runnable hook : hooks) { runtime.addShutdownHook(new Thread(hook)); LOGGER.trace("Registered shutdown hook {}", hook.getClass().getName()); } }
From source file:org.apache.smscserver.main.CommandLine.java
/** * Add shutdown hook./*from ww w . ja va 2 s.c o m*/ */ private void addShutdownHook(final SmscServer engine) { // create shutdown hook Runnable shutdownHook = new Runnable() { public void run() { System.out.println("Stopping server..."); engine.stop(); } }; // add shutdown hook Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(new Thread(shutdownHook)); }
From source file:org.apache.ftpserver.main.CommandLine.java
/** * Add shutdown hook./*from ww w . j ava2 s . c o m*/ */ private void addShutdownHook(final FtpServer engine) { // create shutdown hook Runnable shutdownHook = new Runnable() { public void run() { System.out.println("Stopping server..."); engine.stop(); } }; // add shutdown hook Runtime runtime = Runtime.getRuntime(); runtime.addShutdownHook(new Thread(shutdownHook)); }
From source file:org.hydracache.server.bootstrap.SpringContainer.java
SpringContainer(Runtime runtime, String[] configurationLocations) { applicationContext = new ClassPathXmlApplicationContext(configurationLocations); runtime.addShutdownHook(new ShutdownThread()); }
From source file:net.yacy.yacy.java
/** * Starts up the whole application. Sets up all datastructures and starts * the main threads.//w w w.j a va2 s .c om * * @param homePath Root-path where all information is to be found. * @param startupFree free memory at startup time, to be used later for statistics */ private static void startup(final File dataHome, final File appHome, final long startupMemFree, final long startupMemTotal, final boolean gui) { String tmpdir = null; try { // start up System.out.println(copyright); System.out.println(hline); // ensure that there is a DATA directory, if not, create one and if that fails warn and die mkdirsIfNeseccary(dataHome); mkdirsIfNeseccary(appHome); File f = new File(dataHome, "DATA/"); mkdirsIfNeseccary(f); if (!(f.exists())) { System.err.println("Error creating DATA-directory in " + dataHome.toString() + " . Please check your write-permission for this folder. YaCy will now terminate."); System.exit(-1); } // set jvm tmpdir to a subdir for easy cleanup (as extensive use file.deleteonexit waists memory during long runs, as todelete files names are collected and never cleaned up during runtime) // keep this as earlier as possible, as any other class can use the "java.io.tmpdir" property, even the log manager, when the log file pattern uses "%t" as an alias for the tmp directory try { tmpdir = java.nio.file.Files.createTempDirectory("yacy-tmp-").toString(); // creates sub dir in jvm's temp (see System.property "java.io.tempdir") System.setProperty("java.io.tmpdir", tmpdir); } catch (IOException ex) { } // setting up logging f = new File(dataHome, "DATA/LOG/"); mkdirsIfNeseccary(f); f = new File(dataHome, "DATA/LOG/yacy.logging"); final File f0 = new File(appHome, "defaults/yacy.logging"); if (!f.exists() || f0.lastModified() > f.lastModified()) try { Files.copy(f0, f); } catch (final IOException e) { System.out.println("could not copy yacy.logging"); } try { ConcurrentLog.configureLogging(dataHome, new File(dataHome, "DATA/LOG/yacy.logging")); } catch (final IOException e) { System.out.println("could not find logging properties in homePath=" + dataHome); ConcurrentLog.logException(e); } ConcurrentLog.config("STARTUP", "YaCy version: " + yacyBuildProperties.getVersion() + "/" + yacyBuildProperties.getSVNRevision()); ConcurrentLog.config("STARTUP", "Java version: " + System.getProperty("java.version", "no-java-version")); ConcurrentLog.config("STARTUP", "Operation system: " + System.getProperty("os.name", "unknown")); ConcurrentLog.config("STARTUP", "Application root-path: " + appHome); ConcurrentLog.config("STARTUP", "Data root-path: " + dataHome); ConcurrentLog.config("STARTUP", "Time zone: UTC" + GenericFormatter.UTCDiffString() + "; UTC+0000 is " + System.currentTimeMillis()); ConcurrentLog.config("STARTUP", "Maximum file system path length: " + OS.maxPathLength); f = new File(dataHome, "DATA/yacy.running"); final String conf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator); if (!f.createNewFile()) ConcurrentLog.severe("STARTUP", "WARNING: the file " + f + " can not be created!"); try { new FileOutputStream(f).write(Integer.toString(OS.getPID()).getBytes()); } catch (final Exception e) { } // write PID f.deleteOnExit(); FileChannel channel = null; FileLock lock = null; try { channel = new RandomAccessFile(f, "rw").getChannel(); lock = channel.tryLock(); // lock yacy.running } catch (final Exception e) { } try { sb = new Switchboard(dataHome, appHome, "defaults/yacy.init".replace("/", File.separator), conf); } catch (final RuntimeException e) { ConcurrentLog.severe("STARTUP", "YaCy cannot start: " + e.getMessage(), e); System.exit(-1); } //sbSync.V(); // signal that the sb reference was set // switch the memory strategy MemoryControl.setStandardStrategy(sb.getConfigBool("memory.standardStrategy", true)); // save information about available memory at startup time sb.setConfig("memoryFreeAfterStartup", startupMemFree); sb.setConfig("memoryTotalAfterStartup", startupMemTotal); // start gui if wanted if (gui) YaCyApp.start("localhost", sb.getLocalPort()); // hardcoded, forced, temporary value-migration sb.setConfig("htTemplatePath", "htroot/env/templates"); double oldVer; try { String tmpversion = sb.getConfig(Seed.VERSION, ""); if (tmpversion.isEmpty()) { // before 1.83009737 only the svnRevision nr was in config (like 9737) tmpversion = yacyBuildProperties.getVersion(); int oldRev = Integer.parseInt(sb.getConfig("svnRevision", "0")); if (oldRev > 1) { oldVer = Double.parseDouble(tmpversion) + oldRev / 100000000.0; } else { oldVer = Double.parseDouble(yacyBuildProperties.getLongVersion()); // failsafe (assume current version = no migration) } } else { oldVer = Double.parseDouble(tmpversion); } } catch (final NumberFormatException e) { oldVer = 0.0d; } final double newRev = Double.parseDouble(yacyBuildProperties.getLongVersion()); sb.setConfig(Seed.VERSION, yacyBuildProperties.getLongVersion()); sb.setConfig("applicationRoot", appHome.toString()); sb.setConfig("dataRoot", dataHome.toString()); // create some directories final File htRootPath = new File(appHome, sb.getConfig(SwitchboardConstants.HTROOT_PATH, SwitchboardConstants.HTROOT_PATH_DEFAULT)); mkdirIfNeseccary(htRootPath); htDocsPath = sb.getDataPath(SwitchboardConstants.HTDOCS_PATH, SwitchboardConstants.HTDOCS_PATH_DEFAULT); mkdirIfNeseccary(htDocsPath); //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs")); // copy the donate iframe (better to copy this once here instead of doing this in an actual iframe in the search result) importDonationIFrame(sb, htDocsPath); // create default notifier picture File notifierFile = new File(htDocsPath, "notifier.gif"); if (!notifierFile.exists()) try { Files.copy(new File(htRootPath, "env/grafics/empty.gif"), notifierFile); } catch (final IOException e) { } final File htdocsReadme = new File(htDocsPath, "readme.txt"); if (!(htdocsReadme.exists())) try { FileUtils.copy(("This is your root directory for individual Web Content\r\n" + "\r\n" + "Please place your html files into the www subdirectory.\r\n" + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy or\r\n" + "http://<your-ip>:<your-port>/www\r\n" + "\r\n" + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n" + "This directory shares it's content with the applications htroot path, so you\r\n" + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n" + "\r\n").getBytes(), htdocsReadme); } catch (final IOException e) { System.out.println("Error creating htdocs readme: " + e.getMessage()); } shareDefaultPath = new File(htDocsPath, "share"); mkdirIfNeseccary(shareDefaultPath); shareDumpDefaultPath = new File(shareDefaultPath, "dump"); mkdirIfNeseccary(shareDumpDefaultPath); migration.migrate(sb, oldVer, newRev); // delete old release files final int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30); yacyRelease.deleteOldDownloads(sb.releasePath, deleteOldDownloadsAfterDays); // set user-agent HTTPClient.setDefaultUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent); // start main threads final int port = sb.getLocalPort(); try { // start http server YaCyHttpServer httpServer; httpServer = new Jetty9HttpServerImpl(port); httpServer.startupServer(); sb.setHttpServer(httpServer); // TODO: this has no effect on Jetty (but needed to reflect configured value and limit is still used) ConnectionInfo.setServerMaxcount(sb.getConfigInt("connectionsMax", ConnectionInfo.getMaxcount())); ConcurrentLog.info("STARTUP", httpServer.getVersion()); // open the browser window final boolean browserPopUpTrigger = sb .getConfig(SwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true"); if (browserPopUpTrigger) try { final String browserPopUpPage = sb.getConfig(SwitchboardConstants.BROWSER_POP_UP_PAGE, "ConfigBasic.html"); //boolean properPW = (sb.getConfig(SwitchboardConstants.ADMIN_ACCOUNT, "").isEmpty()) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0); //if (!properPW) browserPopUpPage = "ConfigBasic.html"; /* YaCy main startup process must not hang because browser opening is long or fails. * Let's open try opening the browser in a separate thread */ new Thread("Browser opening") { @Override public void run() { Browser.openBrowser(("http://localhost:" + port) + "/" + browserPopUpPage); } }.start(); // Browser.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage); } catch (final Throwable e) { // cannot open browser. This may be normal in headless environments //Log.logException(e); } // enable browser popup, http server is ready now sb.tray.setReady(); //regenerate Locales from Translationlist, if needed final File locale_source = sb.getAppPath("locale.source", "locales"); final String lang = sb.getConfig("locale.language", ""); // on lang=browser all active translation should be checked (because any could be requested by client) List<String> langlist; if (lang.endsWith("browser")) langlist = Translator.activeTranslations(); // get all translated languages else { langlist = new ArrayList<String>(); langlist.add(lang); } for (String tmplang : langlist) { if (!tmplang.equals("") && !tmplang.equals("default") && !tmplang.equals("browser")) { //locale is used String currentRev = null; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream( new File(sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"), tmplang + "/version")))); currentRev = br.readLine(); // may return null } catch (final IOException e) { //Error } finally { try { br.close(); } catch (IOException ioe) { ConcurrentLog.warn("STARTUP", "Could not close " + tmplang + " version file"); } } if (currentRev == null || !currentRev.equals(sb.getConfig(Seed.VERSION, ""))) { try { //is this another version?! final File sourceDir = new File(sb.getConfig(SwitchboardConstants.HTROOT_PATH, SwitchboardConstants.HTROOT_PATH_DEFAULT)); final File destDir = new File( sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"), tmplang); if (new TranslatorXliff().translateFilesRecursive(sourceDir, destDir, new File(locale_source, tmplang + ".lng"), "html,template,inc", "locale")) { //translate it //write the new Versionnumber final BufferedWriter bw = new BufferedWriter( new PrintWriter(new FileWriter(new File(destDir, "version")))); bw.write(sb.getConfig(Seed.VERSION, "Error getting Version")); bw.close(); } } catch (final IOException e) { } } } } // initialize number formatter with this locale if (!lang.equals("browser")) // "default" is handled by .setLocale() Formatter.setLocale(lang); // registering shutdown hook ConcurrentLog.config("STARTUP", "Registering Shutdown Hook"); final Runtime run = Runtime.getRuntime(); run.addShutdownHook(new shutdownHookThread(sb, shutdownSemaphore)); // save information about available memory after all initializations //try { sb.setConfig("memoryFreeAfterInitBGC", MemoryControl.free()); sb.setConfig("memoryTotalAfterInitBGC", MemoryControl.total()); System.gc(); sb.setConfig("memoryFreeAfterInitAGC", MemoryControl.free()); sb.setConfig("memoryTotalAfterInitAGC", MemoryControl.total()); //} catch (final ConcurrentModificationException e) {} // wait for server shutdown try { sb.waitForShutdown(); } catch (final Exception e) { ConcurrentLog.severe("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(), e); } // shut down Array.terminate(); ConcurrentLog.config("SHUTDOWN", "caught termination signal"); httpServer.stop(); ConcurrentLog.config("SHUTDOWN", "server has terminated"); sb.close(); } catch (final Exception e) { ConcurrentLog.severe("STARTUP", "Unexpected Error: " + e.getClass().getName(), e); //System.exit(1); } if (lock != null) lock.release(); if (channel != null) channel.close(); } catch (final Exception ee) { ConcurrentLog.severe("STARTUP", "FATAL ERROR: " + ee.getMessage(), ee); } finally { } if (tmpdir != null) FileUtils.deletedelete(new File(tmpdir)); // clean up temp dir (set at startup as subdir of system.propery "java.io.tmpdir") ConcurrentLog.config("SHUTDOWN", "goodbye. (this is the last line)"); ConcurrentLog.shutdown(); shutdownSemaphore.release(1000); try { System.exit(0); } catch (final Exception e) { } // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790) }