[英]JPA optimistic locking vs synchronized Java method
Using JPA optimistic locking we can control via a @Version field if a database table has been updated by another transaction at the same time, allowing to have reliable data stored in database. 使用JPA乐观锁定,我们可以通过@Version字段控制数据库表是否已被另一个事务同时更新,从而可以将可靠的数据存储在数据库中。
If a Java application has only one CRUD service in charge of an specific entity in database, we could synchronize its methods and manage the order the information is stored in database too. 如果Java应用程序只有一个CRUD服务负责数据库中的特定实体,我们可以同步其方法并管理信息在数据库中存储的顺序。
So my question is, what's the difference between those scenarios? 所以我的问题是,这些方案之间有什么区别? Does exist any advantage of performance or even best practices to follow?
绩效或最佳实践是否存在优势?
Drawbacks of method synchronization: 方法同步的缺点:
Think of synchronization as pessimistic locking: you have to reserve the lock before you start working as opposed to checking if you violated the lock only when you finished working (optimistic lock during commit). 将同步视为悲观锁定:您必须在开始工作之前保留锁定,而不是仅在完成工作后检查是否违反了锁定(提交期间的乐观锁定)。 The two serve very different purposes:
两者的用途截然不同:
In general: do not use synchronization to lock on entities, there is pessimistic lock support in JPA which locks on the actual DB row: http://docs.oracle.com/javaee/6/tutorial/doc/gkjiu.html 通常:不要使用同步来锁定实体,JPA中提供了悲观锁定支持,可以锁定实际的数据库行: http : //docs.oracle.com/javaee/6/tutorial/doc/gkjiu.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.