如何在Java Spring中创建Future Task Threads Atomic(Transactional)

时间:2015-11-19 19:51:31

标签: java multithreading spring threadpool futuretask

我试图使每个线程成为原子。我已经尝试在执行方法之后使用代理注释来开始和结束事务但是它没有工作,并且我尝试在类级别和方法级别使用事务注释都不起作用。那么如何使线程成为原子。

测试类/驱动程序类

public class TestTaskExecutor {
    @Autowired
    MyTaskExecutor myTaskExecutor;
    @Autowired(required = true)
    SessionFactory sessionFactory;
    Logger logger = LoggerFactory.getLogger(TestTaskExecutor.class.getName());

@Test
public void testTaskExecutor() {

    FutureTask[] futureTasks = new FutureTask[2];
    for (int i = 0; i < 2; i++) {
        TestTable newTable = new TestTable();
        String rollId = "test"+ Integer.toString(i);
        newTable.setRollid(anid);
        TestCallable testCallable = new TestCallable(newTable);
        futureTasks[i] = new FutureTask<Integer>(testCallable);
        myTaskExecutor.executeTask(futureTasks[i]);
    }
    int count = 0;
    for (FutureTask<Integer> f : futureTasks) {
        try {
            int i = f.get();
            count = count + i;

        } catch (InterruptedException e) {
            logger.error(e.getLocalizedMessage());
        } catch (ExecutionException e) {
            logger.error(e.getLocalizedMessage());
        }
    }
    Assert.assertEquals("not equal", 2, count);
}
}

我的可调用实现

public class TestCallable implements Callable<Integer> {
TestTable testTable;
@Autowired(required = true)
SessionFactory sessionFactory;
Logger logger = LoggerFactory.getLogger(TestCallable.class.getName());

private SecureRandom random;

{
    random = new SecureRandom();
}

public TestCallable(TestTable testTable){
    this.testTable = testTable;
}
@Override
public Integer call() throws Exception {
    Session session = DBConnection.getInstance().getCurrentSession();
    this.testTable.setName(generateRandomString());
    try{
        logger.info("in save or update");
        session.saveOrUpdate(this.testTable);
    }
    catch(Exception e){
        logger.info("in error");
        logger.info(e.getLocalizedMessage());
        return 0;
    }
    return 1;

}

private String generateRandomString(){
    return new BigInteger(130, random).toString(32);
}
}

任务执行者代码

public class MyTaskExecutor {
private TaskExecutor taskExecutor;
private static Logger logger = LoggerFactory.getLogger(MyTaskExecutor.class);

public MyTaskExecutor(TaskExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
}

@Transactional
public void executeTask(FutureTask futureTask) {
    if (futureTask != null) {
        try {
            taskExecutor.execute(futureTask);
        } catch (Exception ex) {
            logger.error("Error in thread", ex);
            throw new RuntimeException(ex);
        }
    }
}

}

错误消息失败,因为不是活动事务。

0 个答案:

没有答案