limax进程关闭-Stopper

使用JMX管理Java进程状态

1.建立一个MBean接口

public interface StopperMXBean {
    void setStopTime(long delayseconds);
    long getStopTime();
}

2.实现类

public static final class Stopper implements StopperMXBean {
static final ReentrantLock shutdownAlarmLock = new ReentrantLock();
static final Condition shutdownAlarm = shutdownAlarmLock.newCondition();
static long stopTime = -1L;

public Stopper() {
    JMXRegister(this, "limax.xmlconfig:type=Service,name=Stopper");
}

public void doWait() {
    while (true) {
        try {
            shutdownAlarmLock.lockInterruptibly();
        } catch (final InterruptedException ex) {
            break;
        }
        try {
            if (stopTime < 0)
                shutdownAlarm.await();
            else {
                final long now = System.currentTimeMillis();
                if (now >= stopTime)
                    break;
                else
                    shutdownAlarm.awaitUntil(new Date(stopTime));
            }
        } catch (final InterruptedException ex) {
            break;
        } finally {
            shutdownAlarmLock.unlock();
        }
    }
}

@Override
public long getStopTime() {
    final long time;
    shutdownAlarmLock.lock();
    try {
        time = stopTime;
    } finally {
        shutdownAlarmLock.unlock();
    }
    return time <= 0 ? time : time - System.currentTimeMillis();
}

@Override
public void setStopTime(long milliseconds) {
    if (milliseconds < 0)
        return;
    shutdownAlarmLock.lock();
    try {
        stopTime = System.currentTimeMillis() + milliseconds;
        shutdownAlarm.signalAll();
    } finally {
        shutdownAlarmLock.unlock();
    }
}

3.Mbeans注册管理

static Resource mbeans = Resource.create(MBeans.root(), () -> {});

static public void JMXRegister(Object object, String name) {
    MBeans.register(mbeans, object, name);
}

4.进程开启与Stopper注册

private static Stopper stopper;

public static void run(String servicexmlfilename) throws Exception {
    try {
        stopper = new Stopper();
        parentFile = new File(servicexmlfilename).getParentFile();
        if (parentFile == null)
            parentFile = new File(".");
        load(servicexmlfilename);
        startNetEngine();
        stopper.doWait();
        stopNetEngine();
    } catch (Throwable e) {
        e.printStackTrace();
        System.exit(-1);
    } finally {
        mbeans.close();
    }
}

5.留出对外调用的接口

public static void stop(long milliseconds) {
    stopper.setStopTime(milliseconds);
}

6.总结:
(1)通过JMX外部可以方便的停止进程。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值