java kill信号_基于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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值