读书人

Spring的事务管理难题剖析(4):多线程的

发布时间: 2012-12-22 12:05:05 作者: rapoo

Spring的事务管理难点剖析(4):多线程的困惑
Spring通过单实例化Bean简化多线程问题


由于Spring的事务管理器是通过线程相关的ThreadLocal来保存数据访问基础设施(也即Connection实例),再结合IoC和AOP实现高级声明式事务的功能,所以Spring的事务天然地和线程有着千丝万缕的联系。
我们知道Web容器本身就是多线程的,Web容器为一个HTTP请求创建一个独立的线程(实际上大多数Web容器采用共享线程池),所以由此请求所牵涉到的Spring容器中的Bean也是运行于多线程的环境下。在绝大多数情况下,Spring的Bean都是单实例的(singleton),单实例Bean的最大好处是线程无关性,不存在多线程并发访问的问题,也就是线程安全的。
一个类能够以单实例的方式运行的前提是“无状态”:即一个类不能拥有状态化的成员变量。我们知道,在传统的编程中,DAO必须持有一个Connection,而Connection即是状态化的对象。所以传统的DAO不能做成单实例的,每次要用时都必须创建一个新的实例。传统的Service由于内部包含了若干个有状态的DAO成员变量,所以其本身也是有状态的。
但是在Spring中,DAO和Service都以单实例的方式存在。Spring是通过ThreadLocal将有状态的变量(如Connection等)本地线程化,达到另一个层面上的“线程无关”,从而实现线程安全。Spring不遗余力地将有状态的对象无状态化,就是要达到单实例化Bean的目的。
由于Spring已经通过ThreadLocal的设施将Bean无状态化,所以Spring中单实例Bean对线程安全问题拥有了一种天生的免疫能力。不但单实例的Service可以成功运行于多线程环境中,Service本身还可以自由地启动独立线程以执行其他的Service。

启动独立线程调用事务方法

package com.baobaotao.multithread;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.stereotype.Service;import org.apache.commons.dbcp.BasicDataSource;@Service("userService")public class UserService extends BaseService {    @Autowired    private JdbcTemplate jdbcTemplate;    @Autowired    private ScoreService scoreService;    public void logon(String userName) {        System.out.println("before userService.updateLastLogonTime method...");        updateLastLogonTime(userName);        System.out.println("after userService.updateLastLogonTime method...");        //scoreService.addScore(userName, 20);//①在同一线程中调用scoreService#addScore()                //②在一个新线程中执行scoreService#addScore()        Thread myThread = new MyThread(this.scoreService, userName, 20);//使用一个新线程运行        myThread.start();    }    public void updateLastLogonTime(String userName) {        String sql = "UPDATE t_user u SET u.last_logon_time = ? WHERE user_name =?";        jdbcTemplate.update(sql, System.currentTimeMillis(), userName);    }        //③负责执行scoreService#addScore()的线程类    private class MyThread extends Thread {        private ScoreService scoreService;        private String userName;        private int toAdd;        private MyThread(ScoreService scoreService, String userName, int toAdd) {            this.scoreService = scoreService;            this.userName = userName;            this.toAdd = toAdd;        }        public void run() {            try {                Thread.sleep(2000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("before scoreService.addScor method...");            scoreService.addScore(userName, toAdd);            System.out.println("after scoreService.addScor method...");        }    }}

将日志级别设置为DEBUG,执行UserService#logon()方法,观察以下输出日志:

读书人网 >编程

热点推荐