Java uses Shutdownhook to shut down system resources

Source: Internet
Author: User

Java Close Hook

In a Java program, you can turn off the resource when the program exits by adding a close hook.
Use Runtime.addshutdownhook (Thread hook) to add closure hooks to the JVM

    publicvoidaddShutdownHook(Thread hook) {        SecurityManager sm = System.getSecurityManager();        ifnull) {            sm.checkPermission(new RuntimePermission("shutdownHooks"));        }        ApplicationShutdownHooks.add(hook);    }

Shutdownhook (Thread hook) method, you can register a JVM closed hook, this hook can be called in the following several scenarios:
1) Program Exit normally
2) use System.exit ()
3) interrupts triggered by the terminal using CTRL + C
4) System shutdown
5) Kill the process using the kill PID command

Using the close hook in eclipse

When you close a program by tapping terminate directly in Eclipse, the closing of the hook is not triggered. Using kill-9 under Linux does not trigger hooks.

If you want to implement the ability to close hooks in eclipse, you need another thread to listen to the console and shut down the system when you enter enter in the console

/** * <p> class Description: Enter enter key to close system </p> * <p> Created by: Wang Cheng </p> * <p> created: June 8, 2015 PM 5:23:31 </p> */ public  Span class= "Hljs-class" >class  exitthread  extends  thread  {  Private  Log logger = Logfactory.getlog (GetClass ()); public  void  run  () {Logger.info ( "press ENTER to call System.exit (0)" ); try  {System.in.read (); } catch  (IOException e) {e.printstacktrace (); } system.exit (0 ); }}
Close the configuration of resources in spring

When using spring, you can configure Destroy-method in the bean to implement some processing of the bean when the system shuts down.

    <bean id="simpleHandler" class="com.tiamaes.gjds.socket.server.SimpleHanlder" destroy-method="destroy">        <property name="annotationSocketServiceFactory" ref="annotationSocketServiceFactory" />    </bean>
    //此方法需要声明void,并且没有任何参数    publicvoiddestroy(){        logger.info("Stop socket handler.");    }
Java+spring implementation closes spring when the program exits
/** * <p> Description: System close hook for closing spring Resources </p> * <p> Creator: Wang Cheng </p> * <p> created: June 8, 2015 PM 5:06:4 6 </p> * * Public  class shutdownhook extends Thread {    PrivateLog logger = Logfactory.getlog (GetClass ());PrivateConfigurableapplicationcontext ApplicationContext; Public Shutdownhook(Configurableapplicationcontext ApplicationContext) {Super(); This. ApplicationContext = ApplicationContext; }@Override       Public void Run() {Logger.info ("Start Clean the login info.");//Clean up the logon status of all users when the system shuts downTbdxpuserloginstatusrepository repository = Applicationcontext.getbean (Tbdxpuserloginstatusrepository.class);        Repository.deleteall ();        Applicationcontext.close (); Logger.info ("Socket server Shutdown"); }}

You need to pass in the spring context when the Shutdownhook is instantiated, and call the Close method of ApplicationContext when the system shuts down.

    publicstaticvoidmain(String[] args) {        ClassPathXmlApplicationContext ct =                 new ClassPathXmlApplicationContext("applicationContext.xml");        Runtime.getRuntime().addShutdownHook(new ShutDownHook(ct));        //在正式部署时不需要下面的代码,这段代码仅供调试时使用        new ExitThread();        thread.start();    }

The final effect is as follows

 -- .- the  the: +:Wuyi,233INFO Classpathxmlapplicationcontext-refreshing org.Springframework.Context.Support.[Email protected]2e52Cdcc:startupDate [Tue June the  the: +:WuyiCst -]; root of context hierarchy2015-06-09 09:43:52,263 INFO xmlbeandefinitionreader-loading XML bean definitions from c Lass Path Resource[ApplicationContext.XML]2015-06-09 09:43:55,559 INFO xmlbeandefinitionreader-loading XML Bean Definitions from class path resource[ApplicationContext-service.XML]2015-06-09 09:43:55,724 INFO xmlbeandefinitionreader-loading XML Bean Definitions from class path resource[ApplicationContext-db.XML]2015-06-09 09:44:01,358 INFO propertyplaceholderconfigurer-loading properties file from class path resource[Jdbc.Properties]2015-06-09 09:44:02,687 Info mlog-mlog clients using slf4j logging.2015-06-09 09:44:06,563 info C3p0registry-ini Tializing C3p0-0.9.5-pre9[Built ,-october- the Geneva: .: , -0700; Debug? true; TraceTen]2015-06-09 09:44:08,930 INFO localcontainerentitymanagerfactorybean-building JPA container entitymanagerfactory For persistence unit ' Oracle ' 2015-06-09 09:44:09,251 INFO loghelper-hhh000204:processing persistenceunitinfo[Name:oracle...]2015-06-09 09:44:13,400 Info version-hhh000412:hibernate Core {4.3.7.final}2015-06-09 09:44:13,404 info Environment- HHH000206:hibernate.properties not found2015-06-09 09:44:13,439 INFO environment-hhh000021:bytecode provider Name: javassist2015-06-09 09:44:15,016 INFO version-hcann000001:hibernate Commons Annotations {4.0.5.final}2015-06-09 09:44 : 15,660 info dialect-hhh000400:using dialect:org.hibernate.dialect.oracle10gdialect2015-06-09 09:44:15,739 Info LobC Reatorbuilder-hhh000422:disabling contextual LOB creation as connection was null2015-06-09 09:44:16,056 INFO Astqueryt Ranslatorfactory-hhh000397:using astquerytranslatorfactory2015-06-09 09:44:21,032 INFO ehcachemanagerfactorybean-i Nitializing EhCache cachemanager2015-06-09 09:44:21,977 INFO exitthread-press ENTER to call System.exit (0) 2015-06-09 0 9:54:23,694 Info Shutdownhook-start Clean the login info.2015-06-09 09:54:23,787 info abstractpoolbackeddatasource-i Nitializing c3p0 Pool ... coM.mchange.v2.c3p0.combopooleddatasource  [Acquireincrement -5, acquireretryattempts -0, Acquireretrydelay - +, Autocommitonclose -true, automatictesttable -NULL, Breakafteracquirefailure -false, Checkouttimeout - the, Connectioncustomizerclassname -NULL, Connectiontesterclassname -Com.Mchange.V2.C3p0.Impl.Defaultconnectiontester, Contextclassloadersource -Caller, DataSourceName -1Hge7dt991ndh1jygiycad|7402FFF0, Debugunreturnedconnectionstacktraces -false, description -NULL, Driverclass -Oracle.Jdbc.Oracledriver, extensions -{}, Factoryclasslocation -NULL, forceignoreunresolvedtransactions -false, Forceusenameddriverclass -false, Identitytoken -1Hge7dt991ndh1jygiycad|7402FFF0, Idleconnectiontestperiod -0, initialpoolsize -5, Jdbcurl -jdbc:oracle:thin:@192.168. the.:1521: ORCL, Maxadministrativetasktime -0, Maxconnectionage -0, MaxIdleTime -36000, maxidletimeexcessconnections -1800, maxpoolsize - -, maxstatements -0, maxstatementsperconnection -0, minpoolsize -5, Numhelperthreads -3, Preferredtestquery -NULL, Privilegespawnedthreads -false, properties -{User=******, password=******}, Propertycycle -0, Statementcachenumdeferredclosethreads -0, Testconnectiononcheckin -false, Testconnectiononcheckout -false, Unreturnedconnectiontimeout -0, Useroverrides -{}, Usestraditionalreflectiveproxies -false ]Hibernate:select tbdxpuserl0_. session_id as Session_id1_1_, tbdxpuserl0_. Create_time as Create_time2_1_, tbdxpuserl0_. Ip_addr as Ip_addr3_1_, tbdxpuserl0_. Login_time as login_time4_1_, tbdxpuserl0_.status as status5_1_, tbdxpuserl0_. user_id as user_id6_1_, tbdxpuserl0_.username as username7_1_ from Tb_dxp_user_login_status tbdxpuserl0_2015-06-09 09:54:25,555 INFO classpathxmlapplicationcontext-closing org[email protected]2e52cdcc:startup Date[Tue June the  the: +:WuyiCst -]; root of the context hierarchy2015-06-09 09:54:25,556 INFO ehcachemanagerfactorybean-shutting down EhCache cachemanage r2015-06-09 09:54:25,574 Info simplehanlder-stop socket handler.2015-06-09 09:54:25,576 Info localcontainerentitymanag  Erfactorybean-closing JPA entitymanagerfactory for persistence unit ' Oracle ' 2015-06-09 09:54:25,579 INFO Shutdownhook -Socket server shutdown

This method can realize the function of shutting down the resource and cleaning the cache data when the system exits, which is a very useful function.

Some of the content comes from other posts, and the code is the code in my project. If there is any similarity, please do not be offended.
This article only describes how to use, as to the principle of mom and Google

Java uses Shutdownhook to shut down system resources

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.