主题
SystemServerInitThreadPool(初始化线程池) · 源码分析
逐行注释源码
以下为 SystemServerInitThreadPool.java 全文(共 368 行),基于 AOSP,保留原有英文 Javadoc,逐字段、逐方法补了中文注释。该类是 SystemServer 启动阶段使用的固定大小线程池:系统服务通过 submit() 提交初始化任务,线程池在 SystemService.PHASE_BOOT_COMPLETED 之后关闭,此后不应再提交新任务。
一、文件说明与导入声明
Apache 2.0 许可声明、包名 com.android.server,以及 Slog、Process、ConcurrentUtils、TimingsTraceAndSlog 等依赖。
java
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.server;
import android.annotation.NonNull;
import android.os.Build;
import android.os.Process;
import android.util.Dumpable;
import android.util.Slog;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.ConcurrentUtils;
import com.android.internal.util.Preconditions;
import com.android.server.am.StackTracesDumpHelper;
import com.android.server.utils.TimingsTraceAndSlog;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;二、类定义与字段
SystemServerInitThreadPool 实现 Dumpable 接口,作为单例管理一个固定大小线程池;字段含线程数、底层 ExecutorService、待执行任务描述列表与关闭标记。
java
/**
* SystemServer 初始化阶段使用的线程池。
*
* <p>系统服务可以在启动期间通过 {@link #submit(Runnable, String)} 提交任务执行。
* 线程池将在 {@link SystemService#PHASE_BOOT_COMPLETED} 之后关闭。
*
* <p>此后不应再提交新任务。</p>
*
* @hide
*/
public final class SystemServerInitThreadPool implements Dumpable {
/** 日志标签,用于所有 Slog 日志输出。 */
private static final String TAG = SystemServerInitThreadPool.class.getSimpleName();
/** 关闭时等待所有任务完成的超时时间,单位为毫秒。 */
private static final int SHUTDOWN_TIMEOUT_MILLIS = 20000;
/** 当前编译版本是否为可调试版本(eng/userdebug),控制是否输出详细日志。 */
private static final boolean IS_DEBUGGABLE = Build.IS_DEBUGGABLE;
/** 锁对象,用于同步访问单例实例。 */
private static final Object LOCK = new Object();
/** 线程池单例实例,受 {@link #LOCK} 保护。 */
@GuardedBy("LOCK")
private static SystemServerInitThreadPool sInstance;
/** 线程池中的线程数量(等于 CPU 可用核心数),仅用于 dump() 输出。 */
private final int mSize; // used by dump() only
/** 底层的 ExecutorService,负责管理线程池。 */
private final ExecutorService mService;
/** 待执行任务的描述列表,用于任务跟踪和调试。 */
@GuardedBy("mPendingTasks")
private final List<String> mPendingTasks = new ArrayList<>();
/** 标记线程池是否已关闭。 */
@GuardedBy("mPendingTasks")
private boolean mShutDown;三、构造函数与单例获取
私有构造函数按 CPU 核心数创建固定线程池;getInstance() 在 LOCK 下返回单例,若已关闭则抛 IllegalStateException。
java
/**
* 私有构造函数,强制单例模式。
* 创建一个固定大小的线程池,线程数等于 CPU 可用核心数。
*/
private SystemServerInitThreadPool() {
// 获取当前设备的 CPU 可用核心数,作为线程池大小
mSize = Runtime.getRuntime().availableProcessors();
// 打印信息日志,记录创建的线程数量
Slog.i(TAG, "Creating instance with " + mSize + " threads");
// 创建固定大小的线程池,线程名为 "system-server-init-thread"
// 线程优先级设为前台优先级 THREAD_PRIORITY_FOREGROUND
mService = ConcurrentUtils.newFixedThreadPool(mSize,
"system-server-init-thread", Process.THREAD_PRIORITY_FOREGROUND);
}
/**
* 获取线程池的单例实例。
*
* @return 单例实例
* @throws IllegalStateException 如果线程池已被关闭
*/
static SystemServerInitThreadPool getInstance() {
// 声明局部变量,用于返回实例
SystemServerInitThreadPool instance;
// 获取 LOCK 锁,确保线程安全地访问单例
synchronized (LOCK) {
// 前置条件检查:如果 sInstance 为 null,说明线程池已关闭或未启动
Preconditions.checkState(sInstance != null, "Cannot get " + TAG
+ " - it has been shut down");
// 将单例引用赋值给局部变量
instance = sInstance;
}
// 返回获取到的实例
return instance;
}四、任务提交(submit / submitTask)
对外两个 submit 重载分别接收 Runnable / Callable 与描述;submitTask 为任务包装 trace 追踪与日志,并把描述加入待处理列表、完成后移除。
java
/**
* 提交一个 Runnable 任务执行,返回的 Future 在成功时返回 null。
*
* @param runnable 要执行的任务
* @param description 任务的人类可读描述,用于日志和调试
* @return 表示任务待完成的 Future
* @throws IllegalStateException 如果线程池尚未启动或已被关闭
*/
public static @NonNull Future<?> submit(@NonNull Runnable runnable,
@NonNull String description) {
// 前置条件检查:description 不能为 null
Objects.requireNonNull(description, "description cannot be null");
// 将 Runnable 包装为 Callable,调用内部提交方法
return getInstance().submitTask(Executors.callable(runnable), description);
}
/**
* 提交一个 Callable 任务执行,返回包含任务结果的 Future。
*
* @param callable 要执行的任务
* @param description 任务的人类可读描述,用于日志和调试
* @param <T> 任务返回结果的类型
* @return 表示任务待完成的 Future,包含执行结果
* @throws IllegalStateException 如果线程池尚未启动或已被关闭
*/
public static <T> @NonNull Future<T> submit(@NonNull Callable<T> callable,
@NonNull String description) {
// 前置条件检查:description 不能为 null
Objects.requireNonNull(description, "description cannot be null");
// 直接调用内部提交方法
return getInstance().submitTask(callable, description);
}
/**
* 内部方法,将任务提交到执行器服务。
* 为 Callable 包装 trace 追踪和日志输出,并跟踪待处理任务。
*
* @param callable 要执行的任务
* @param description 任务的人类可读描述
* @param <T> 结果的类型
* @return 表示任务待完成的 Future
*/
private <T> @NonNull Future<T> submitTask(@NonNull Callable<T> callable,
@NonNull String description) {
// 获取待处理任务列表的锁
synchronized (mPendingTasks) {
// 前置条件检查:如果已关闭,则不允许提交新任务
Preconditions.checkState(!mShutDown, TAG + " already shut down");
// 将任务描述添加到待处理列表,用于跟踪
mPendingTasks.add(description);
}
// 提交任务到线程池执行,返回 Future
return mService.submit(() -> {
// 创建异步 trace 日志,用于性能追踪
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
// 开始 trace:标记任务执行开始
traceLog.traceBegin("InitThreadPoolExec:" + description);
// 如果是可调试版本,打印调试日志记录任务开始
if (IS_DEBUGGABLE) {
Slog.d(TAG, "Started executing " + description);
}
// 声明结果变量
T result = null;
try {
// 执行实际的 Callable 任务
result = callable.call();
} catch (RuntimeException e) {
// 捕获运行时异常,打印错误日志
Slog.e(TAG, "Failure in " + description + ": " + e, e);
// 结束 trace 追踪
traceLog.traceEnd();
// 重新抛出异常,让调用者处理
throw e;
}
// 获取待处理任务列表的锁
synchronized (mPendingTasks) {
// 从待处理列表中移除已完成的任务描述
mPendingTasks.remove(description);
}
// 如果是可调试版本,打印调试日志记录任务完成
if (IS_DEBUGGABLE) {
Slog.d(TAG, "Finished executing " + description);
}
// 结束 trace 追踪
traceLog.traceEnd();
// 返回任务执行结果
return result;
});
}五、启动与关闭(start / shutdown / dumpStackTraces)
start() 创建单例;shutdown() 在 PHASE_BOOT_COMPLETED 后关闭线程池,最多等待 20 秒,超时或被中断时先 dump 堆栈再强制关停并抛异常。dumpStackTraces() 收集本进程堆栈供诊断。
java
/**
* 启动线程池,创建单例实例。
*
* <p>注意:</p> 只能由 {@link SystemServer} 调用。
*
* @throws IllegalStateException 如果线程池已启动且尚未关闭
*/
static void start() {
// 获取 LOCK 锁,确保线程安全地创建单例
synchronized (LOCK) {
// 前置条件检查:如果 sInstance 不为 null,说明已经启动过
Preconditions.checkState(sInstance == null, TAG + " already started");
// 创建新的线程池实例,赋值给单例引用
sInstance = new SystemServerInitThreadPool();
}
}
/**
* 关闭线程池,等待所有任务完成。
*
* <p>注意:</p> 只能在 {@code PHASE_BOOT_COMPLETED} 发送给
* {@link SystemService 系统服务} 之后调用。
*
* @throws IllegalStateException 如果关闭超时或被中断
*/
static void shutdown() {
// 打印调试日志,标记关闭请求
Slog.d(TAG, "Shutdown requested");
// 获取 LOCK 锁,确保关闭操作的线程安全
synchronized (LOCK) {
// 创建 trace 追踪对象,用于性能测量
TimingsTraceAndSlog t = new TimingsTraceAndSlog();
// 开始 trace:标记等待线程池关闭的阶段
t.traceBegin("WaitInitThreadPoolShutdown");
// 检查单例实例是否已为空(已被关闭或从未启动)
if (sInstance == null) {
// 结束 trace
t.traceEnd();
// 打印 WTF 级别日志(What a Terrible Failure),记录异常堆栈
Slog.wtf(TAG, "Already shutdown", new Exception());
// 直接返回,无需重复关闭
return;
}
// 获取待处理任务列表的锁,设置关闭标志
synchronized (sInstance.mPendingTasks) {
// 标记线程池已进入关闭状态,阻止新任务提交
sInstance.mShutDown = true;
}
// 优雅关闭:不再接受新任务,等待已提交任务完成
sInstance.mService.shutdown();
// 标记是否所有任务都已正常终止
final boolean terminated;
try {
// 阻塞等待,最多等待 SHUTDOWN_TIMEOUT_MILLIS(20秒)
terminated = sInstance.mService.awaitTermination(SHUTDOWN_TIMEOUT_MILLIS,
TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// 捕获中断异常,恢复线程中断状态
Thread.currentThread().interrupt();
// 转储堆栈信息以便调试
dumpStackTraces();
// 结束 trace
t.traceEnd();
// 抛出 IllegalStateException,表示初始化被中断
throw new IllegalStateException(TAG + " init interrupted");
}
// 如果未在超时时间内正常终止(存在未完成的任务或死锁)
if (!terminated) {
// 必须在 shutdownNow() 之前调用 dumpStackTraces(),
// 因为 shutdownNow() 会强制中断线程,之后无法获取堆栈
dumpStackTraces();
}
// 强制关闭:取消所有等待执行的任务,返回未启动的任务列表
final List<Runnable> unstartedRunnables = sInstance.mService.shutdownNow();
// 再次检查:如果之前未正常终止,说明有关闭异常
if (!terminated) {
// 创建副本,收集未完成的任务描述
final List<String> copy = new ArrayList<>();
synchronized (sInstance.mPendingTasks) {
// 将待处理任务列表复制到本地
copy.addAll(sInstance.mPendingTasks);
}
// 结束 trace
t.traceEnd();
// 抛出异常,包含未启动和未完成的任务信息,便于排查
throw new IllegalStateException("Cannot shutdown. Unstarted tasks "
+ unstartedRunnables + " Unfinished tasks " + copy);
}
// 正常关闭:将单例实例置为 null,使其可被垃圾回收器回收
sInstance = null; // 置空,使其可被 GC 回收
// 打印成功关闭的调试日志
Slog.d(TAG, "Shutdown successful");
// 结束 trace
t.traceEnd();
}
}
/**
* 辅助方法,调用 StackTracesDumpHelper.dumpStackTraces()。
* 当关闭失败或被中断时,转储当前进程的堆栈信息。
*/
private static void dumpStackTraces() {
// 创建进程 ID 列表
final ArrayList<Integer> pids = new ArrayList<>();
// 添加当前进程 ID
pids.add(Process.myPid());
// 调用堆栈转储辅助方法,转储当前进程及关键 native 进程的堆栈
StackTracesDumpHelper.dumpStackTraces(pids,
/* processCpuTracker= */null, /* lastPids= */null,
CompletableFuture.completedFuture(Watchdog.getInterestingNativePids()),
/* logExceptionCreatingFile= */null, /* subject= */null,
/* criticalEventSection= */null, /* extraHeaders= */ null,
Runnable::run, /* latencyTracker= */null);
}六、状态转储(getDumpableName / dump)
实现 Dumpable 接口:getDumpableName 返回类简单名;dump() 输出是否有实例、线程数、底层 service、是否已关闭及待处理任务列表。
java
/**
* 返回用于转储此对象的名称。
*
* @return 类的简单名称
*/
@Override
public String getDumpableName() {
// 返回当前类的简单名称(不含包名)
return SystemServerInitThreadPool.class.getSimpleName();
}
/**
* 转储线程池的当前状态,用于调试。
*
* @param pw 用于输出转储信息的 PrintWriter
* @param args 额外的参数(未使用)
*/
@Override
public void dump(PrintWriter pw, String[] args) {
// 获取 LOCK 锁,安全地读取单例状态
synchronized (LOCK) {
// 输出单例实例是否存在
pw.printf("has instance: %b\n", (sInstance != null));
}
// 输出线程池的线程数量
pw.printf("number of threads: %d\n", mSize);
// 输出 ExecutorService 的状态信息
pw.printf("service: %s\n", mService);
// 获取待处理任务列表的锁
synchronized (mPendingTasks) {
// 输出线程池是否已关闭
pw.printf("is shutdown: %b\n", mShutDown);
// 获取当前待处理任务数量
final int pendingTasks = mPendingTasks.size();
// 如果没有待处理任务
if (pendingTasks == 0) {
// 输出无待处理任务
pw.println("no pending tasks");
} else {
// 输出待处理任务数量和列表
pw.printf("%d pending tasks: %s\n", pendingTasks, mPendingTasks);
}
}
}
}