基于ThreadLocal的POJO嵌套事务实现
嵌套事务原理与设计目标
在企业级应用中,事务的嵌套执行是常见需求。通过嵌套事务机制,内层操作可独立提交或回滚,而不影响外层事务状态。本方案采用纯POJO实现,结合ThreadLocal保障多线程环境下的事务隔离。
核心接口定义
public interface TransactionContext {
Connection getConnection();
void begin();
void commit();
void rollback();
}
栈式事务管理器实现
public class NestedTransactionManager implements TransactionContext {
private final ThreadLocal
多线程事务隔离机制
通过ThreadLocal绑定每个线程独立的连接栈实例,确保不同线程间事务互不干扰。每个线程拥有独立的事务上下文,避免共享状态引发的数据异常。
测试场景演示
public class TransactionTest implements Runnable {
private final int index;
private final String threadName;
public TransactionTest(int index, String name) {
this.index = index;
this.threadName = name;
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 3; i++) {
new Thread(new TransactionTest(i * 10, "Worker_" + i)).start();
}
}
@Override
public void run() {
TransactionContext tx = new NestedTransactionManager();
try {
// 外层事务
tx.begin();
Connection conn = tx.getConnection();
executeInsert(conn, "INSERT INTO test_tran (emp_id, name) VALUES ('1" + index + "', '" + threadName + index + "')");
// 内层事务
tx.begin();
conn = tx.getConnection();
executeInsert(conn, "INSERT INTO test_tran (emp_id, name) VALUES ('2" + index + "', '" + threadName + index + "')");
tx.commit(); // 内层提交
tx.rollback(); // 外层回滚
} catch (Exception e) {
e.printStackTrace();
}
}
private void executeInsert(Connection conn, String sql) throws SQLException {
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.executeUpdate();
}
}
}
运行结果分析
日志输出显示每个线程创建独立连接,内层事务成功提交后,外层事务被回滚,最终数据库仅保留内层事务数据。该行为验证了嵌套事务的正确性与隔离性。