基于kill信号优雅的关闭JAVA程序

    linux下其他jar包

# java -jar program.jar &

   当要停止程序时很多人先会考虑使用 kill -9 $pid ,强制程序退出,这有可能造成程序处理进程被半路中断,造成写入数据不完整。为了能优雅的退出,考虑通过捕捉USR2信号安全退出,以HttpServer为例。

package com.uar.daemon;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import sun.misc.Signal;
import sun.misc.SignalHandler;

import com.sun.net.httpserver.HttpServer;
import com.uar.bean.ConfigSetting;

public class HttpServerTest implements SignalHandler {
	
	private static Logger logger = LogManager.getLogger(HttpServerTest.class);
	
	private HttpServer server;
	private ExecutorService httpThreadPool;
	
	@Override
	public void handle(Signal sn) {
		logger.info("Signal [" + sn.getName() + "] is received, stopServer soon...");
		stopServer();
		logger.info("Stop successfully.");
	}
	
	public static void main(String[] args){
		HttpServerTest main = new HttpServerTest();
		// 捕捉USR2信号
		Signal.handle(new Signal("USR2"), main);
		main.startServer();
	}
	
	public void startServer() {
		int port = 5555;
		String context = "/KillTest";
		int maxConnections = 50;
		try {
			InetSocketAddress addr = new InetSocketAddress(port);
			server = HttpServer.create(addr, maxConnections);
			
			server.createContext(context, new ServerHandler());
			httpThreadPool = Executors.newCachedThreadPool();
			server.setExecutor(httpThreadPool);
			server.start();
		} catch (IOException e) {
			logger.error(e);
		}
	}	
	
	/**
	 * 安全的关闭HttpServer监听服务
	 */
	private void stopServer() {
		server.stop(1);
		httpThreadPool.shutdown();
	}
}

 

server.stop()

stop

public abstract void stop(int delay)
stops this server by closing the listening socket and disallowing any new exchanges from being processed. The method will then block until all current exchange handlers have completed or else when approximately delay seconds have elapsed (whichever happens sooner). Then, all open TCP connections are closed, the background thread created by start() exits, and the method returns. Once stopped, a HttpServer cannot be re-used.
Parameters:
   delay - the maximum time in seconds to wait until exchanges have finished.
Throws:
   IllegalArgumentException - if delay is less than zero.

 

    

你可能感兴趣的:(JAVA)