キラル信号に基づいて優雅にJAVAプログラムをクローズします。

2474 ワード

linuxの下に他のjarのカバンがあります。
# java -jar program.jar &
   プログラムを停止する場合、多くの人が先にKill-9$pidを使って強制的にプログラムを終了することを考慮します。プログラム処理が途中で中断され、データの書き込みが不完全になる可能性があります。優雅に退出できるように、USR 2信号を捕捉して安全に退出することを考え、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.