主题
SystemServerInitThreadPool(初始化线程池) · 如何使用
本节回答「SystemServerInitThreadPool 怎么创建与关闭、谁在提交任务、怎么观察它」,内容均基于前文源码分析中的真实信息整理。该类标注 @hide、仅供系统进程内部使用,应用无法直接调用,因此这里的「使用」指的是框架如何调用它、以及如何观察其行为。
怎么创建与关闭:start() → 提交任务 → shutdown()
线程池是单例,生命周期与 SystemServer 启动过程绑定:
- 创建:SystemServer 在启动早期调用
SystemServerInitThreadPool.start(),在LOCK下校验「尚未创建」(sInstance == null,否则抛IllegalStateException: already started)后 new 出单例;构造函数按 CPU 核心数创建固定线程池(线程名前缀system-server-init-thread、前台优先级)。 - 使用:启动期间各系统服务通过
submit()提交初始化任务,任务被包装上 trace 追踪与日志后交由线程池执行。 - 关闭:在
SystemService.PHASE_BOOT_COMPLETED之后调用shutdown()——先置mShutDown = true阻止新任务,再mService.shutdown()并awaitTermination(20000ms)等待全部任务完成;成功后置sInstance = null释放单例。类注释明确:「此后不应再提交新任务」。
谁在提交任务:submit() 的两个重载
系统服务在启动期间把初始化工作以任务形式提交进来。对外两个静态重载,签名如下(均要求 description 非空):
java
public static Future<?> submit(Runnable runnable, String description)
public static <T> Future<T> submit(Callable<T> callable, String description)两者都经 getInstance() 拿到单例后委托给 submitTask():先把 description 加入 mPendingTasks 待处理列表,再把任务提交给线程池。每个任务执行时会被 TimingsTraceAndSlog 包一层异步 trace(名为 InitThreadPoolExec:<description>),并在可调试版本(Build.IS_DEBUGGABLE)下用 Slog.d 打印 Started executing / Finished executing 日志;任务正常完成后从 mPendingTasks 移除描述,抛 RuntimeException 时记错误日志并重新抛出。description 因此同时承担 trace 标签、日志标识与待处理任务跟踪三重作用——提交时给一个可读的名字很有意义。
关闭失败会怎样:超时即抛异常并 dump 堆栈
shutdown() 不是「尽力而为」:若 awaitTermination 在 20 秒内未全部完成,或等待期间被中断,它会先调用 dumpStackTraces()(收集本进程 Process.myPid() 及 Watchdog.getInterestingNativePids() 关心的 native 进程堆栈),再 shutdownNow() 强制关停,并抛出 IllegalStateException(消息列出未启动与未完成的任务)。由于它运行在 system_server 进程,这一异常若未被调用方捕获,会使 system_server 崩溃并触发系统重启——这本身就是「开机阶段某个初始化任务卡住超时」的兜底信号。若 shutdown() 在 sInstance 已为 null 时再被调用,则记一条 Slog.wtf(... "Already shutdown" ...) 并直接返回。
怎么观察:dump() 与 logcat
该类实现 Dumpable,dump(PrintWriter, args) 输出以下字段,可直接用于排查开机卡顿与任务堆积:
text
has instance: <true|false>
number of threads: <mSize>
service: <底层 ExecutorService 的 toString>
is shutdown: <true|false>
<N> pending tasks: [<未完成的 description 列表>] // 无任务时为 "no pending tasks"日志侧:TAG 为类简单名 SystemServerInitThreadPool。创建时打印 Creating instance with <N> threads;可调试版本下每个任务打印 Started executing <description> / Finished executing <description>;关闭时打印 Shutdown requested 与成功后的 Shutdown successful。因此用 logcat -s SystemServerInitThreadPool 即可观察线程池的创建、各任务执行与关闭过程,配合 dump() 里的 pending tasks 列表能快速定位是哪个初始化任务卡住了开机。