深挖 Java 核心技术底层源码:从原理到实战(附阿里部署调优)
底层源码是理解 Java 技术本质的关键,也是高级开发 / 面试的核心考点。本文聚焦 JavaSE、JavaWeb、MyBatis 三大核心技术的底层源码,从核心类 / 接口的实现逻辑入手,结合源码注释和调试技巧,帮助开发者穿透 “使用层”,掌握 “原理层”,并补充阿里云部署时的源码级调优方案。
一、JavaSE 核心源码解析
HashMap(JDK 8)核心源码
HashMap 是 JavaSE 中最常用的容器,其底层实现是 “数组 + 链表 + 红黑树”,核心源码如下(关键片段):
java
运行
public class HashMap extends AbstractMap implements Map, Cloneable, Serializable {
// 核心常量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认初始容量16(2^4)
static final float DEFAULT_LOAD_FACTOR = 0.75f; // 默认负载因子
static final int TREEIFY_THRESHOLD = 8; // 链表转红黑树阈值
static final int UNTREEIFY_THRESHOLD = 6; // 红黑树转链表阈值// 核心数组(桶)
transient Node[] table;
// 元素个数
transient int size;
// 扩容阈值(size > threshold 触发扩容)
int threshold;
// 负载因子
final float loadFactor;// 构造方法(初始化负载因子)
public HashMap(int initialCapacity, float loadFactor) {if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); // 计算扩容阈值(向上取整为2的幂)}
// 核心方法:put元素
public V put(K key, V value) {return putVal(hash(key), key, value, false, true);}
// 真正的put实现(核心)
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {Node<K,V>[] tab; Node<K,V> p; int n, i; // 1. 数组为空则初始化(首次put时) if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 2. 计算桶位置(n-1 & hash 等价于 hash % n,效率更高) if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); // 桶为空,直接新建节点 else { Node<K,V> e; K k; // 3. 桶中第一个节点匹配(hash+equals) if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; // 4. 红黑树节点 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); // 5. 链表节点 else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); // 链表长度>=8,转红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); break; } // 找到匹配节点,跳出循环 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } // 6. 节点已存在,替换值 if (e != null) { V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); // 空实现(LinkedHashMap重写) return oldValue; } } ++modCount; // 7. 元素个数超过阈值,扩容 if (++size > threshold) resize(); afterNodeInsertion(evict); // 空实现(LinkedHashMap重写) return null;}
// 扩容核心方法
final Node[] resize() {Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { // 超过最大容量,不再扩容 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } // 扩容为原来的2倍(newCap = oldCap * 2) else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // 阈值也扩容2倍 } else if (oldThr > 0) // 初始容量由threshold指定(构造方法) newCap = oldThr; else { // 首次初始化(使用默认值) newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } // 计算新阈值 if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; // 创建新数组,迁移数据 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) // 单个节点,直接迁移 newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) // 红黑树节点,拆分 ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // 链表节点,拆分(高位/低位链表) Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; // 原位置:hash & oldCap == 0 if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } // 新位置:hash & oldCap != 0(原位置 + oldCap) else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab;}
}
核心源码解读:
哈希计算:hash(key) 方法对 key 的 hashCode 进行扰动,减少哈希冲突;
扩容机制:每次扩容为 2 倍,保证n-1 & hash的散列均匀性;
链表转红黑树:链表长度≥8 且数组长度≥64 时触发,提升查询效率(O (n)→O (logn));
线程安全:HashMap 非线程安全,多线程环境下扩容可能导致死循环(推荐使用 ConcurrentHashMap)。ThreadPoolExecutor(线程池)核心源码
线程池是 Java 多线程的核心,ThreadPoolExecutor 的核心源码如下:
java
运行
public class ThreadPoolExecutor extends AbstractExecutorService {
// 核心线程数
private final int corePoolSize;
// 最大线程数
private final int maximumPoolSize;
// 空闲线程存活时间
private final long keepAliveTime;
// 工作队列(阻塞队列)
private final BlockingQueue workQueue;
// 线程工厂
private final ThreadFactory threadFactory;
// 拒绝策略
private final RejectedExecutionHandler handler;// 线程池状态(高3位)+ 线程数(低29位)
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1;// 线程池状态(RUNNING < SHUTDOWN < STOP < TIDYING < TERMINATED)
private static final int RUNNING = -1 << COUNT_BITS; // 接受新任务+处理队列任务
private static final int SHUTDOWN = 0 << COUNT_BITS; // 不接受新任务+处理队列任务
private static final int STOP = 1 << COUNT_BITS; // 不接受新任务+不处理队列任务+中断正在执行的任务
private static final int TIDYING = 2 << COUNT_BITS; // 所有任务完成,线程数为0
private static final int TERMINATED = 3 << COUNT_BITS; // 终止状态// 核心方法:提交任务
public void execute(Runnable command) {if (command == null) throw new NullPointerException(); int c = ctl.get(); // 1. 工作线程数 < 核心线程数,创建新核心线程 if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } // 2. 线程池RUNNING且任务加入队列成功 if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); // 二次检查:线程池已非RUNNING,移除任务并执行拒绝策略 if (! isRunning(recheck) && remove(command)) reject(command); // 工作线程数为0,创建非核心线程 else if (workerCountOf(recheck) == 0) addWorker(null, false); } // 3. 队列满,创建非核心线程(直到最大线程数) else if (!addWorker(command, false)) reject(command); // 最大线程数已满,执行拒绝策略}
// 创建工作线程(核心)
private boolean addWorker(Runnable firstTask, boolean core) {retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // 检查线程池状态(SHUTDOWN状态且队列空/任务非空,不创建线程) if (rs >= SHUTDOWN && ! (rs == SHUTDOWN && firstTask == null && ! workQueue.isEmpty())) return false; for (;;) { int wc = workerCountOf(c); // 线程数超过容量/核心线程数(core=true)/最大线程数(core=false) if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)) return false; // CAS增加线程数,成功则跳出循环 if (compareAndIncrementWorkerCount(c)) break retry; c = ctl.get(); // CAS失败,重新读取ctl if (runStateOf(c) != rs) continue retry; } } boolean workerStarted = false; boolean workerAdded = false; Worker w = null; try { // 创建Worker(封装线程和任务) w = new Worker(firstTask); final Thread t = w.thread; if (t != null) { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); // 加锁(保证workers集合线程安全) try { int rs = runStateOf(ctl.get()); // 再次检查线程池状态 if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) { if (t.isAlive()) // 线程已启动,抛异常 throw new IllegalThreadStateException(); workers.add(w); // 添加到workers集合 int s = workers.size(); if (s > largestPoolSize) largestPoolSize = s; workerAdded = true; } } finally { mainLock.unlock(); } if (workerAdded) { t.start(); // 启动线程 workerStarted = true; } } } finally { if (! workerStarted) addWorkerFailed(w); // 启动失败,清理资源 } return workerStarted;}
// 内部类:Worker(实现Runnable,封装线程和任务)
private final class Worker extends AbstractQueuedSynchronizer implements Runnable {final Thread thread; Runnable firstTask; long completedTasks; Worker(Runnable firstTask) { setState(-1); // 初始化AQS状态,避免runWorker前被中断 this.firstTask = firstTask; this.thread = threadFactory.newThread(this); // 创建线程 } public void run() { runWorker(this); // 执行任务 }}
// 执行任务核心逻辑
final void runWorker(Worker w) {Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; w.unlock(); // 释放锁(允许中断) boolean completedAbruptly = true; try { // 循环获取任务(核心:getTask()从队列取任务) while (task != null || (task = getTask()) != null) { w.lock(); // 加锁(防止线程池停止时中断任务) // 检查线程池状态,必要时中断线程 if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted()) wt.interrupt(); try { beforeExecute(wt, task); // 空实现(子类重写) Throwable thrown = null; try { task.run(); // 执行任务 } catch (RuntimeException x) { thrown = x; throw x; } catch (Error x) { thrown = x; throw x; } catch (Throwable x) { thrown = x; throw new Error(x); } finally { afterExecute(task, thrown); // 空实现(子类重写) } } finally { task = null; w.completedTasks++; w.unlock(); } } completedAbruptly = false; } finally { processWorkerExit(w, completedAbruptly); // 任务执行完毕,退出worker }}
}
核心源码解读:
线程池状态:通过ctl原子变量维护状态 + 线程数,高 3 位是状态,低 29 位是线程数;
任务执行流程:核心线程→工作队列→非核心线程→拒绝策略;
Worker 类:封装线程和任务,通过 AQS 实现锁机制,保证任务执行的线程安全;
拒绝策略:默认AbortPolicy(抛异常),还有CallerRunsPolicy(调用者执行)、DiscardPolicy(丢弃)、DiscardOldestPolicy(丢弃最旧任务)。
二、JavaWeb 核心源码解析- Servlet(Tomcat 实现)核心源码
Tomcat 是 JavaWeb 的主流容器,其 Servlet 实现核心在org.apache.catalina.core包下,关键源码如下:
java
运行
// Servlet核心接口(Javax定义)
public interface Servlet {
void init(ServletConfig config) throws ServletException;
ServletConfig getServletConfig();
void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
String getServletInfo();
void destroy();
}
// Tomcat的Servlet基类实现
public abstract class HttpServlet extends GenericServlet {
// 核心方法:service(分发GET/POST请求)
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod(); // 获取请求方法(GET/POST/PUT/DELETE等)
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
doGet(req, resp); // 处理GET请求
} else {
long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
if (ifModifiedSince < lastModified) {
setLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
setLastModified(resp, lastModified);
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
doPost(req, resp); // 处理POST请求
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
} else {
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
// 模板方法(子类重写)
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
}
// Tomcat的Servlet包装类(管理Servlet生命周期)
public class StandardWrapperValve extends ValveBase {
@Override
public final void invoke(Request request, Response response) throws IOException, ServletException {
// 获取Servlet包装类
StandardWrapper wrapper = (StandardWrapper) getContainer();
Servlet servlet = null;
Context context = (Context) wrapper.getParent();
// 1. 检查Servlet是否可访问
if (!context.getPrivileged() && SecurityUtil.isPackageProtectionEnabled()) {
if (!SecurityUtil.checkPermission(wrapper, request)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
// 2. 加载并初始化Servlet(单例)
try {
servlet = wrapper.allocate(); // 获取Servlet实例(首次调用init)
} catch (ServletException e) {
throw e;
} catch (Throwable e) {
throw new ServletException(sm.getString("standardWrapper.allocate"), e);
}
// 3. 执行Servlet的service方法
try {
// 设置请求/响应对象
request.setServlet(servlet);
request.setServletPath(wrapper.getServletPath());
// 调用Servlet的service方法
servlet.service(request.getRequest(), response.getResponse());
} catch (ServletException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Throwable e) {
throw new ServletException(sm.getString("standardWrapper.service"), e);
} finally {
// 4. 释放Servlet(归还给池)
wrapper.deallocate(servlet);
}
// 5. 检查Servlet是否需要销毁
if (wrapper.getAvailable() == 0) {
wrapper.unload();
}
}
}
核心源码解读:
Servlet 生命周期:init()(首次请求时执行,单例)→ service()(每次请求执行)→ destroy()(容器关闭时执行);
请求分发:HttpServlet的service()方法根据请求方法(GET/POST)分发到对应的doXxx()方法;
Tomcat 管理:StandardWrapper负责 Servlet 的实例化、初始化和销毁,保证 Servlet 单例(默认)。
- Filter(过滤器)核心源码
java
运行
// Filter核心接口(Javax定义)
public interface Filter {
void init(FilterConfig filterConfig) throws ServletException;
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;
void destroy();
}
// Tomcat的FilterChain实现
public final class ApplicationFilterChain implements FilterChain {
// Filter数组
private Filter[] filters = new Filter[0];
// 当前执行的Filter索引
private int pos = 0;
// Filter总数
private int n = 0;
// 目标Servlet
private Servlet servlet = null;
// 添加Filter
void addFilter(Filter filter) {
if (n == filters.length) {
// 扩容
Filter[] newFilters = new Filter[n + INCREMENT];
System.arraycopy(filters, 0, newFilters, 0, n);
filters = newFilters;
}
filters[n++] = filter;
}
// 核心方法:执行Filter链
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if (pos < n) {
// 获取当前Filter
Filter filter = filters[pos++];
// 执行Filter的doFilter方法
filter.doFilter(request, response, this);
} else {
// Filter链执行完毕,执行目标Servlet
servlet.service(request, response);
}
}
}
核心源码解读:
Filter 链执行:ApplicationFilterChain通过数组存储 Filter,按顺序执行doFilter(),最后执行 Servlet;
链式调用:Filter 的doFilter()中调用chain.doFilter(),实现 Filter 的依次执行;
拦截范围:Filter 可拦截请求 / 响应,实现统一编码、登录校验等功能。
三、MyBatis 核心源码解析
- SqlSessionFactory(会话工厂)核心源码
java
运行
// SqlSessionFactory核心接口
public interface SqlSessionFactory {
SqlSession openSession();
SqlSession openSession(boolean autoCommit);
SqlSession openSession(Connection connection);
SqlSession openSession(TransactionIsolationLevel level);
// 重载方法...
}
// MyBatis默认实现:DefaultSqlSessionFactory
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private final Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
@Override
public SqlSession openSession(boolean autoCommit) {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, autoCommit);
}
// 核心:从数据源创建SqlSession
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
// 1. 获取环境配置(数据源、事务管理器)
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
// 2. 创建执行器(Executor)
final Executor executor = configuration.newExecutor(tx, execType);
// 3. 创建DefaultSqlSession(核心会话)
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // 关闭事务
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
}
Mapper 代理(核心)源码
MyBatis 通过动态代理实现 Mapper 接口与 SQL 的绑定,核心源码如下:
java
运行
// Mapper代理工厂
public class MapperProxyFactory {
private final Class mapperInterface;
private final Map methodCache = new ConcurrentHashMap<>();public MapperProxyFactory(Class mapperInterface) {
this.mapperInterface = mapperInterface;}
// 创建Mapper代理对象
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy mapperProxy) {// JDK动态代理 return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy);}
}
// Mapper代理类(实现InvocationHandler)
public class MapperProxy implements InvocationHandler, Serializable {
private final SqlSession sqlSession;
private final Class mapperInterface;
private final Map methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
// 核心:代理方法调用
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Object类的方法(toString/hashCode)直接调用
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else {
// 获取MapperMethod并执行
return cachedMapperMethod(method).execute(sqlSession, args);
}
}
// 缓存MapperMethod(避免重复创建)
private MapperMethod cachedMapperMethod(Method method) {
return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
}
}
// MapperMethod(封装SQL执行逻辑)
public class MapperMethod {
private final SqlCommand command;
private final MethodSignature method;
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, mapperInterface, method);
}
// 执行SQL
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
// 根据SQL类型(INSERT/UPDATE/DELETE/SELECT)执行对应方法
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args); // 查询多条
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args); // 查询Map
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args); // 查询游标
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param); // 查询单条
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
// 处理返回值为空的情况
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
}
核心源码解读:
动态代理:MyBatis 通过 JDK 动态代理为 Mapper 接口生成代理对象,调用接口方法时触发MapperProxy.invoke();
SQL 执行:MapperMethod根据 SQL 类型(SELECT/INSERT/UPDATE/DELETE)调用SqlSession的对应方法;
缓存机制:methodCache缓存MapperMethod,避免重复解析接口方法。
四、阿里云部署源码级调优
- HashMap 调优(生产环境)
初始容量设置:根据预估数据量设置初始容量(如预估 1000 条,设置initialCapacity=1024),避免频繁扩容;
java
运行
// 优化前:默认初始容量16,会多次扩容
Map map = new HashMap<>();
// 优化后:指定初始容量,减少扩容次数
Map map = new HashMap<>(1024);
阿里云 ECS 调优:在高并发场景下,替换为ConcurrentHashMap,避免线程安全问题;
java
运行
// 高并发场景推荐
Map map = new ConcurrentHashMap<>(1024); - 线程池调优(阿里云 ECS)
根据 ECS 实例规格调整线程池参数:
java
运行
// 2核4G ECS推荐配置
ThreadPoolExecutor executor = new ThreadPoolExecutor(
4, // 核心线程数(CPU核心数2)
8, // 最大线程数(CPU核心数4)
60L, // 空闲线程存活时间
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1000), // 工作队列(容量1000)
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略(调用者执行,避免抛异常)
); - MyBatis 调优(阿里云 RDS)
开启二级缓存(谨慎):在只读场景下开启,提升查询性能;
xml
数据源连接池调优:适配阿里云 RDS,调整连接池参数;
xml
五、源码阅读技巧与实战 - 源码阅读方法
断点调试:在 IDEA 中导入源码(JDK/MyBatis/Tomcat),通过断点跟踪执行流程;
核心入口:从常用方法入手(如HashMap.put()、ThreadPoolExecutor.execute()),逐步深入;
注释解读:重点关注源码注释,理解设计思路;
画流程图:梳理核心逻辑(如 HashMap 扩容、线程池任务执行)。 - 常见源码面试题
HashMap 为什么线程不安全?
扩容时的链表环问题(JDK7)、多线程 put 时的元素覆盖问题(JDK8);
线程池核心参数有哪些?如何设置?
核心线程数、最大线程数、存活时间、工作队列、拒绝策略;根据 CPU 核心数和业务场景设置;
MyBatis 的 Mapper 代理原理?
JDK 动态代理,MapperProxy实现InvocationHandler,调用接口方法时执行对应的 SQL。
六、总结
底层源码是 Java 开发的 “内功”,掌握核心类的实现逻辑,不仅能应对面试,更能在生产环境中精准调优。本文覆盖了 JavaSE(HashMap、线程池)、JavaWeb(Servlet、Filter)、MyBatis(SqlSession、Mapper 代理)三大核心技术的源码,同时补充了阿里云部署时的源码级调优方案。
建议开发者:
从高频使用的类入手(如 HashMap、ThreadPoolExecutor),逐步深入;
结合调试工具,跟踪代码执行流程;
在阿里云环境中,根据实例规格调整源码级参数,提升性能。
扩展学习资源
JDK 源码:OpenJDK 官方仓库;
MyBatis 源码:MyBatis GitHub;
Tomcat 源码:Tomcat 官方仓库;
阿里云调优文档:ECS 性能优化、RDS 最佳实践。