使用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外部可以方便的停止进程。