How to handle application closure in Java?

Having a console application, a server accepting several connections from clients, can there be a listener or an event in closing the application? In this case, I want all connected clients to gently disconnect before the application really closes.

Any solution? Thanks!

+4
source share
2 answers

Do you want to use the hook off:

Runtime.getRuntime().addShutdownHook(theHookThread); 

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

+7
source

Should closing an application mean an operating system that kills the server process?

In this situation, the server does not know that it is killed. It will disconnect existing connections.

If, when you close the application, you provide a method for the sys administrator to manually close the server (perhaps by typing "exit" on the server console). Then the closing event will be a custom event, and you will need to code the listeners and inform everyone who has stayed on the server. In this case, it is possible.

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

0
source

Source: https://habr.com/ru/post/898653/


All Articles