简体   繁体   中英

How to handle a closing application event in Java?

Having a console application, a server accepting several connections from clients, is it possible to have a listener or an event on a closing application? I want, in this event, tell all connected clients to gently disconnect before the application really closes itself.

Any solution? Thank you!

You want to use a shutdown hook:

Runtime.getRuntime().addShutdownHook(theHookThread);

So the thread will be run when the JVM shuts down, see here for details.

If by closing application you mean the operating system killing the server process?

In that situation there is no way for the server to know it is being killed. It will drop the existing connections.

If by closing application you provide a method for the sys admin to manually close the server ( probably by typing "exit" at server console ). Then the closing event would be a custom event, and you would have to code the listeners and notify to everyone the server is shutting down. In this scenario it is posible.

Try adding more details about how your server is built or how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM