@Transactional 注解在多线程环境下不生效问题
直接上代码
package com.linzi.risk.indicator.service.impl;
import com.linzi.risk.common.utils.threadpool.ThreadPoolManager;
import com.linzi.risk.indicator.dao.AsyncCommandDao;
import com.linzi.risk.indicator.entity.AsyncCommandEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
/**
* @author chentiefeng
* @date 2018/10/11 14:47
*/
@Component
public class TestTrans {
@Resource
private AsyncCommandDao asyncCommandDao;
@Transactional
public void test() {
AsyncCommandEntity command = new AsyncCommandEntity();
command.setType("test");
command.setBsnNo("1");
command.setBsnType("1");
command.setContent("");
try {
command.setAddIp(InetAddress.getLocalHost().getHostName());
command.setUpdateIp(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
e.printStackTrace();
}
command.setAddTime(new Date());
command.setUpdateTime(new Date());
command.setState("INIT");
asyncCommandDao.insert(command);
TransactionAspectSupport.currentTransactionStatus().flush();
ThreadPoolManager.getInstance().execute(new Runnable() {
@Override
public void run() {
AsyncCommandEntity entity = asyncCommandDao.selectById(command.getId());
System.out.println("Transactional 事务下异步线程查询:" + entity);
if (entity.getId() != null) {
asyncCommandDao.delete(entity.getId());
}
}
});
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
因为插入后睡眠了500毫秒,所以运行结果就是报空指针异常。
不了解的情况下以为TransactionAspectSupport.currentTransactionStatus().flush();方法能手动commit事务,原来不行