如何在另一个线程中启动事务?

时间:2016-01-27 08:01:21

标签: java multithreading spring

Spring 4

我正致力于通过ScheduledThreadPoolExecutor实现可更新缓存。目前看来如下:

public class MyService {

    @Setter
    private MyDao myDao;
    //Immutable
    private volatile Cache cache;

    //Static factory method
    public static MyService create(){
        MyService retVal = new MyService();
        cache = Cache.emptyCache();
        updateCache();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int get(){
         //Retrieving from cache
         return cache.getNext();
    }

    private void updateCache() {
        try{
            ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
            //The runnable should be in a transaction.
            Runnable updateCache;
            //the runnable queries the MyDao,
            //which in turn currently implemented as a DB-dao
            //The cache is assigned after computation
            ses.scheduleWithFixedDelay(updateCache, 0, 60, TimeUnit.SECONDS);
        } catch (Throwable t){ }
    }
}

我的问题是我如何在交易中运行可运行的作业?

只要事务是线程绑定的,

updateCache()注释为@Transactional将不起作用。

1 个答案:

答案 0 :(得分:1)

不要那样安排,使用Spring的scheduling support

public class MyService {

    @Setter
    private MyDao myDao;
    //Immutable
    private volatile Cache cache;

    //Static factory method
    public static MyService create(){
        MyService retVal = new MyService();
        cache = Cache.emptyCache();
        updateCache();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int get(){
         //Retrieving from cache
         return cache.getNext();
    }

    @Transactional
    @Scheduled(fixedDelay=60000)
    public void updateCache() {
            //the runnable queries the MyDao,
            //which in turn currently implemented as a DB-dao
            //The cache is assigned after computation
    }
}

然后添加@EnableScheduling<task:annotation-driven />。有关更多配置选项,另请参阅前面提到的链接。