奇怪的事务处理JavaEE 6

时间:2012-12-22 22:21:29

标签: java transactions java-ee-6 optimistic-locking

目前我正在研究JavaEE 6事务处理,我有点卡住了。

我模拟研讨会预订引擎,有人可以在研讨会上预订一个或多个人。 我的实体看起来像这样:

@Entity
@XmlRootElement
public class Seminar {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Version
    private Long version;

    private Integer freeCapacity;

    ... //getters & setters
}

这是EJB:

@Stateless
public class SeminarBooking {

    @PersistenceContext
    EntityManager em;

    @Inject
    Event<Seminar> txListeners;

    public boolean bookSeminar(Long seminarId, int numberOfPersons) {
        Seminar seminar = em.find(Seminar.class, seminarId);
        Integer freeCapacity = seminar.getFreeCapacity();

        if((freeCapacity - numberOfPersons) >= 0) {
            //setting free capacity after booking 
            seminar.setFreeCapacity(freeCapacity - numberOfPersons);

            txListeners.fire(seminar);
            return true;
        }
        return false;
    }
}

我的事务监听器如下所示:

public class TxListener {
    public void onSuccess(@Observes(during=TransactionPhase.AFTER_SUCCESS) Seminar seminar) {
        //omitted retrieving of minute,second,milli
        logger.fine("Successful booking -- " + minute + ":" + second + ":" + milli + " FreeCapacity: "+seminar.getFreeCapacity());
    }
}

问题是,我在后端并行处理100个线程并获取这样的日志条目:

Successful booking -- 24:50:51 FreeCapacity: 9641
Successful booking -- 24:50:61 FreeCapacity: 9641
Successful booking -- 24:50:54 FreeCapacity: 9641
Successful booking -- 24:50:637 FreeCapacity: 9639

怎么可能有成功(承诺)的交易具有相同的freeCapacity值?

在我看来,第二和第三个交易应抛出OptimisticLockException,因为第一个交易已更新实体的版本字段。因此,第二次和第三次交易应该已经回滚。

我在这里想念一下吗?我该如何解决这个问题?

0 个答案:

没有答案