我尝试将用于统计的登录过程的结果异步保存到数据库中,以节省登录方法期间的时间。但是,如果我将 thread.sleep 添加到异步方法中,登录过程会以某种方式花费更长的时间。这是为什么?我认为身份验证方法不会等待 writeResultToStats 方法完成。
@Stateless
@LocalBean
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
@TransactionManagement(TransactionManagementType.CONTAINER)
public class CustomerBeanTest {
@PersistenceContext(unitName = WebPersistenceUnits.QISADS)
private EntityManager em_local;
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void authenticate(Long loginid, String cmppassword) {
try {
Login l = em_local.find(Login.class, loginid);
String s = l.getPassword();
if (!s.equalsIgnoreCase(cmppassword))
throw new PasswordMissmatchException();
writeResultToStats(loginid, true);
} catch (PasswordMissmatchException e) {
writeResultToStats(loginid, false);
}
}
@Asynchronous
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
private void writeResultToStats(Long loginID, boolean success) {
try { // just for testing
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogUtils log = new LogUtils(this);
Login l = em_local.find(Login.class, loginID);
if (success) {
l.setSuccessLast(new Date());
l.setSuccessCount(l.getSuccessCount()+1);
log.log(Level.INFO, "Update Login Stat Success [%d, %s, %d]", l.getId(), l.getName(), Thread.currentThread().getId());
} else {
l.setFailureLast(new Date());
l.setFailureCount(l.getFailureCount()+1);
log.log(Level.INFO, "Update Login Stat Fail [%d, %s, %d]", l.getId(), l.getName(), Thread.currentThread().getId());
}
}
}