In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you the relevant knowledge about how JAVA can automatically shut down the server. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
Ordinary implementation of the server can not shut down itself, only rely on the operating system to forcibly terminate the service program. Although this method of forcibly terminating the service program is simple and convenient, it can lead to a sudden interruption of the tasks being performed on the server. If the task handled by the server is so important that it is not allowed to be interrupted suddenly, it should be left to the server itself to shut itself down at the appropriate time.
The code is as follows:
EchoServer class
Package ShutdownServer;import java.io.*;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketException;import java.net.SocketTimeoutException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.RejectedExecutionException;import java.util.concurrent.TimeUnit;public class EchoServer {private int port=8000;private ServerSocket serverSocket;private ExecutorService executorService; / / Thread Pool private final int POOL_SIZE=4; / / number of worker threads in the thread pool when a single CPU private int portForShutdown=8001 / / whether the server has closed private Thread shutdownThread=new Thread () {/ / the thread responsible for shutting down the server public void run () {while (! isShutdown) {Socket socketForShutdown=null;try {socketForShutdown=serverSocketShutdown.accept (); BufferedReader br=new BufferedReader (new InputStreamReader (socketForShutdown.getInputStream (); String command=br.readLine (); if (command.equals ("shutdown")) {long beginTime=System.currentTimeMillis () SocketForShutdown.getOutputStream (). Write ("server is shutting down\ r\ n" .getBytes (); isShutdown=true;// requests to close thread pool / / thread pool will no longer receive new tasks, but will continue to execute existing tasks in the work queue executorService.shutdown () / / wait for thread pool to be closed. The timeout for each wait is 30s//. When using awaitTermination, the main thread will be in a state of waiting, waiting for all threads in the thread pool to finish running before continuing to run. / / if the wait time exceeds the specified time, but the thread in the thread pool finishes running, awaitTermination () returns true. Execution split thread has ended / / if the wait time exceeds the specified time, but the thread in the thread pool is not finished, awaitTermination () returns false. Do not execute split threading has ended / / if the waiting time does not exceed the specified time, wait! / / you can use the awaitTermination () method to determine whether there are threads running in the thread pool. While (! executorService.isTerminated ()) executorService.awaitTermination (30, TimeUnit.SECONDS); / / turn off ServerSocketserverSocket.close (); long endTime=System.currentTimeMillis (); socketForShutdown.getOutputStream (). Write (("server shutdown," + "shutdown server uses" + (endTime-beginTime) + "ms\ r\ n") .getBytes (); socketForShutdown.close (); serverSocketShutdown.close (); System.out.println ("server shutdown") } else {socketForShutdown.getOutputStream (). Write ("wrong command\ r\ n" .getBytes ()); socketForShutdown.close ();}} catch (Exception e) {e.printStackTrace ();}; public EchoServer () throws IOException {serverSocket=new ServerSocket (port); / / set the timeout for waiting for a customer connection to 60sserverSocket.setSoTimeout (60000); serverSocketShutdown=new ServerSocket (portForShutdown); / / create thread pool executorService= Executors.newFixedThreadPool (Runtime.getRuntime (). AvailableProcessors () * POOL_SIZE); shutdownThread.start () System.out.println ("server startup");} public void service () {while (! isShutdown) {Socket socket=null;try {/ / may throw SocketTimeoutException and SocketExceptionsocket=serverSocket.accept (); / / set the timeout waiting for customers to send data to 60ssocket.setSoTimeout (60000); / / may throw RejectedExecutionExceptionexecutorService.execute (new Handler (socket)) } catch (SocketTimeoutException e) {/ / do not have to handle exceptions that occur while waiting for a customer connection} catch (RejectedExecutionException e) {try {if (socket! = null) socket.close ();} catch (IOException ex) {return;}} catch (SocketException e) {if (e.getMessage (). IndexOf ("socket closed")! =-1) return;} catch (IOException e) {e.printStackTrace () } public static void main (String [] args) throws IOException {/ / main method throws an exception, and the exception is sent directly to the virtual machine, which directly ends the exception new EchoServer (). Service ();}} / / the task responsible for communicating with a single customer class Handler implements Runnable {private Socket socket;public Handler (Socket socket) {this.socket=socket;} private PrintWriter getWriter (Socket socket) throws IOException {OutputStream socketOut=socket.getOutputStream (); return new PrintWriter (socketOut,true) } private BufferedReader getReader (Socket socket) throws IOException {InputStream socketIn=socket.getInputStream (); return new BufferedReader (new InputStreamReader (socketIn));} public String echo (String msg) {return "echo:" + msg;} @ Overridepublic void run () {try {System.out.println ("New connection accepted" + socket.getInetAddress () + ":" + socket.getPort ()); BufferedReader br=getReader (socket); PrintWriter pw=getWriter (socket); String msg=null / receive and send data until the end of the communication: while ((msg=br.readLine ())! = null) {System.out.println ("from" + socket.getInetAddress () + ":" + socket.getPort () + ">" + msg); pw.println (echo (msg)); if (msg.equals ("bye")) break;}} catch (IOException e) {e.printStackTrace ();} finally {try (socketboxes null) socket.close ();} catch (IOException e) {e.printStackTrace ();}
AdminClient class (responsible for sending the "shutdown" command to EchoServer, shutting down the server)
Package ShutdownServer;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.Socket;public class AdminClient {public static void main (String [] args) {Socket socket=null;try {socket=new Socket ("localhost", 8001); / / send the shutdown command OutputStream socketOut=socket.getOutputStream (); / / Scanner scanner=new Scanner (System.in); / / String order=scanner.next (); socketOut.write ("shutdown\ r\ n" .getBytes ()) / / receive BufferedReader br=new BufferedReader (new InputStreamReader (socket.getInputStream (); String msg=null;while ((msg=br.readLine ())! = null) {System.out.println (msg);}} catch (Exception e) {e.printStackTrace ();} finally {try {e.printStackTrace ();} catch (IOException e) {e.printStackTrace ();}
Client class (client, communicating with server)
Package ShutdownServer;import java.io.*;import java.net.Socket;public class Client {private String host= "localhost"; private int port=8000;private Socket socket;public Client () throws IOException {socket=new Socket (host,port);} private PrintWriter getWriter (Socket socket) throws IOException {OutputStream socketOut=socket.getOutputStream (); return new PrintWriter (socketOut,true);} private BufferedReader getReader (Socket socket) throws IOException {InputStream socketIn=socket.getInputStream (); return new BufferedReader (new InputStreamReader (socketIn));} public void talk () throws IOException {try {BufferedReader br=getReader (socket); PrintWriter pw=getWriter (socket) BufferedReader localReader=new BufferedReader (new InputStreamReader (System.in)); String msg=null;while ((msg=localReader.readLine ())! = null) {pw.println (msg); System.out.println (br.readLine ()); if (msg.equals ("bye")) {break;}} catch (IOException e) {e.printStackTrace ();} finally {try {socket.close ();} catch (IOException e) {e.printStackTrace ();}} public static void main (String args []) throws IOException {new Client (). Talk ();}}
The shutdownThread thread, which is responsible for shutting down the server, has been listening on port 8001 and sets isShutdown to true if it receives a "shutdown" command from AdminClient.
When shutting down the server, we used the most common method, first calling the thread pool's shutdown () method, and then calling the thread pool's awaitTermination () method.
ExecutorService.shutdown (); / wait to close the thread pool. The timeout for each wait is 30s//. When awaitTermination is used, the main thread is in a state of waiting, waiting for all threads in the thread pool to finish running before continuing to run. / / if the wait time exceeds the specified time, but the thread in the thread pool finishes running, awaitTermination () returns true. Execution split thread has ended / / if the wait time exceeds the specified time, but the thread in the thread pool is not finished, awaitTermination () returns false. Do not execute split threading has ended / / if the waiting time does not exceed the specified time, wait! / / you can use the awaitTermination () method to determine whether there are threads running in the thread pool. While (! executorService.isTerminated () executorService.awaitTermination (30, TimeUnit.SECONDS)
After the thread pool executes the shutdown () method, the thread pool will not receive new tasks, and the thread will block by calling the awaitTermination () method, and the thread will not continue to go down until the tasks of all threads in the thread pool are finished.
Running result
First run EchoServer,Client,AdminClient, and then open a client program Client1, which shows that Client1 cannot be added to the thread pool
EchoServer (only shows that Client is connected, not Client1 is connected)
Client
Client2 (send a message to the server and receive a null)
AdminClient (blocked when the Client is not running)
When Client type "bye" to finish running, AdminClient shuts down the server
Client class
EchoServer class
AdminClient class
These are all the contents of the article "how to automatically shut down the server in JAVA". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.