Shutdown

/**
* 虚拟机关闭步骤
* @since 1.3
*/
class Shutdown {
/* 关闭状态 */
private static final int RUNNING = 0;
private static final int HOOKS = 1;
private static final int FINALIZERS = 2;
private static int state = RUNNING; /* Should we run all finalizers upon exit? */
private static boolean runFinalizersOnExit = false;
/**
* The system shutdown hooks are registered with a predefined slot.
* The list of shutdown hooks is as follows:
* (0) Console restore hook
* (1) Application hooks
* (2) DeleteOnExit hook
*/
// 最多可注册的钩子函数个数
private static final int MAX_SYSTEM_HOOKS = 10;
private static final Runnable[] hooks = new Runnable[MAX_SYSTEM_HOOKS]; // 当前运行钩子的索引
private static int currentRunningHook = 0; /* The preceding static fields are protected by this lock */
private static class Lock { };
private static Object lock = new Lock(); /* Lock object for the native halt method */
private static Object haltLock = new Lock(); /* Invoked by Runtime.runFinalizersOnExit */
static void setRunFinalizersOnExit(boolean run) {
synchronized (lock) {
runFinalizersOnExit = run;
}
} /**
* 添加一个关闭钩子
*
* @params slot 目标索引
* @params registerShutdownInProgress 是否允许在关闭过程中注册钩子
* @params hook 待注册的钩子
*/
static void add(int slot, boolean registerShutdownInProgress, Runnable hook) {
synchronized (lock) {
// 目标索引处已经注册了
if (hooks[slot] != null) {
throw new InternalError("Shutdown hook at slot " + slot + " already registered");
} if (!registerShutdownInProgress) {
if (state > RUNNING) {
throw new IllegalStateException("Shutdown in progress");
}
} else {
if (state > HOOKS || state == HOOKS && slot <= currentRunningHook) {
throw new IllegalStateException("Shutdown in progress");
}
}
// 写入钩子
hooks[slot] = hook;
}
} /**
* 运行所有注册的关闭钩子
*/
private static void runHooks() {
for (int i=0; i < MAX_SYSTEM_HOOKS; i++) {
try {
Runnable hook;
synchronized (lock) {
// acquire the lock to make sure the hook registered during
// shutdown is visible here.
currentRunningHook = i;
hook = hooks[i];
}
if (hook != null) {
hook.run();
}
} catch(final Throwable t) {
if (t instanceof ThreadDeath) {
final ThreadDeath td = (ThreadDeath)t;
throw td;
}
}
}
} /**
* 强制关闭虚拟机
*/
static void halt(int status) {
synchronized (haltLock) {
halt0(status);
}
} static native void halt0(int status); /* Wormhole for invoking java.lang.ref.Finalizer.runAllFinalizers */
private static native void runAllFinalizers(); /**
* 实际的关机顺序定义
*/
private static void sequence() {
synchronized (lock) {
/* Guard against the possibility of a daemon thread invoking exit
* after DestroyJavaVM initiates the shutdown sequence
*/
if (state != HOOKS) {
return;
}
}
// 运行所有的关闭钩子
runHooks();
boolean rfoe;
synchronized (lock) {
state = FINALIZERS;
rfoe = runFinalizersOnExit;
}
// 运行 Finalizers
if (rfoe) {
runAllFinalizers();
}
} /**
* Invoked by Runtime.exit, which does all the security checks.
*/
static void exit(int status) {
boolean runMoreFinalizers = false;
synchronized (lock) {
if (status != 0) {
runFinalizersOnExit = false;
}
switch (state) {
case RUNNING: /* Initiate shutdown */
state = HOOKS;
break;
case HOOKS: /* Stall and halt */
break;
case FINALIZERS:
if (status != 0) {
/* Halt immediately on nonzero status */
halt(status);
} else {
/* Compatibility with old behavior:
* Run more finalizers and then halt
*/
runMoreFinalizers = runFinalizersOnExit;
}
break;
}
}
if (runMoreFinalizers) {
runAllFinalizers();
halt(status);
}
synchronized (Shutdown.class) {
/* Synchronize on the class object, causing any other thread
* that attempts to initiate shutdown to stall indefinitely
*/
sequence();
halt(status);
}
} /* Invoked by the JNI DestroyJavaVM procedure when the last non-daemon
* thread has finished. Unlike the exit method, this method does not
* actually halt the VM.
*/
static void shutdown() {
// 修改状态
synchronized (lock) {
switch (state) {
case RUNNING: /* Initiate shutdown */
state = HOOKS;
break;
case HOOKS: /* Stall and then return */
case FINALIZERS:
break;
}
}
// 关机
synchronized (Shutdown.class) {
sequence();
}
}
}

Shutdown 源码阅读的更多相关文章

  1. 《java.util.concurrent 包源码阅读》13 线程池系列之ThreadPoolExecutor 第三部分

    这一部分来说说线程池如何进行状态控制,即线程池的开启和关闭. 先来说说线程池的开启,这部分来看ThreadPoolExecutor构造方法: public ThreadPoolExecutor(int ...

  2. ThreadPoolExecutor 源码阅读

    目录 ThreadPoolExecutor 源码阅读 Executor 框架 Executor ExecutorService AbstractExecutorService 构造器 状态 Worke ...

  3. 【详解】ThreadPoolExecutor源码阅读(二)

    系列目录 [详解]ThreadPoolExecutor源码阅读(一) [详解]ThreadPoolExecutor源码阅读(二) [详解]ThreadPoolExecutor源码阅读(三) AQS在W ...

  4. 【详解】ThreadPoolExecutor源码阅读(一)

    系列目录 [详解]ThreadPoolExecutor源码阅读(一) [详解]ThreadPoolExecutor源码阅读(二) [详解]ThreadPoolExecutor源码阅读(三) 工作原理简 ...

  5. Caddy源码阅读(二)启动流程与 Event 事件通知

    Caddy源码阅读(二)启动流程与 Event 事件通知 Preface Caddy 是 Go 语言构建的轻量配置化服务器.https://github.com/caddyserver/caddy C ...

  6. Flink源码阅读(一)——Flink on Yarn的Per-job模式源码简析

    一.前言 个人感觉学习Flink其实最不应该错过的博文是Flink社区的博文系列,里面的文章是不会让人失望的.强烈安利:https://ververica.cn/developers-resource ...

  7. 【原】FMDB源码阅读(三)

    [原]FMDB源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 FMDB比较优秀的地方就在于对多线程的处理.所以这一篇主要是研究FMDB的多线程处理的实现.而 ...

  8. 【原】FMDB源码阅读(二)

    [原]FMDB源码阅读(二) 本文转载请注明出处 -- polobymulberry-博客园 1. 前言 上一篇只是简单地过了一下FMDB一个简单例子的基本流程,并没有涉及到FMDB的所有方方面面,比 ...

  9. 【原】FMDB源码阅读(一)

    [原]FMDB源码阅读(一) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 说实话,之前的SDWebImage和AFNetworking这两个组件我还是使用过的,但是对于 ...

随机推荐

  1. ChinaCock扫描控件介绍-使用TCCBarcodeScanner引起app闪退

    好几个ChinaCock的朋友说遇到扫码时闪退,进一步总结,都是Android 8的机器上才会出现,今天我也遇到.正好有朋友说,按下面这个改配置文件就可以解决: <!-- 扫描的activity ...

  2. 四、指定Nginx启动用户

    一.nginx指定启动用户 1.参考宝塔的配置 解释:(linux权限管理) 指定用www用户启动nginx,如果你用root启动nginx,万一nginx有漏洞,被提权了,你服务器就GG了 所以指定 ...

  3. opencv,用摄像头识别贴片元件的定位和元件的角度(转载)

    经过半个月学习opencv有点小成果,用摄像头识别贴片元件的定位和元件的角度(转载) (2013-04-17 16:00:22) 转载▼   分类: 学习笔记 先说一下开源的opencv真是一件伟大的 ...

  4. windows通讯之evpp

  5. AngularJS实现数据列表的增加、删除和上移下移等功能实例

      转: http://www.jb51.net/article/91991.htm 这篇文章给大家分享了AngularJS循环实现数据列表的增加.删除和上移下移等基础功能,对大家学习AngularJ ...

  6. .net core 读取appsettings 的配置

    { "Logging": { "IncludeScopes": false, "LogLevel": { "Default&quo ...

  7. dyld: Symbol not found: _OBJC_CLASS_$_xxxx 错误闪退

    dyld: Symbol not found: _OBJC_CLASS_$_xxx 引起的APP闪退可以先查看xxx所属的库,然后将其设为optional 例如dyld: Symbol not fou ...

  8. Python之抓取网页元素

    import urllib.request from bs4 import BeautifulSoup url = "http://www.wal-martchina.com/walmart ...

  9. ip 转发(调度器的路由转发)

    临时开启 [root@proxy ~]# echo > /proc/sys/net/ipv4/ip_forward 永久开启 [root@proxy ~]# vim /etc/sysctl.co ...

  10. 【Python之路】特别篇--Python内置函数

    abs() 求绝对值 i = abs(-100) print(i) # 100 all() 循环里面的参数 如果每个元素都为真,那么all返回值为真  假: 0 False None "&q ...