乐观锁定由具体(Java)示例 [英] Optimistic Locking by concrete (Java) example

查看:136
本文介绍了乐观锁定由具体(Java)示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经花了我的早晨阅读所有的顶部文章,谷歌乐观锁定,我仍然不能真正地得到它。

I have spent my morning reading all the top articles that Google churns up on optimistic locking, and for the life of me, I still don't really get it.

理解乐观锁定包括添加一列用于跟踪记录的版本,并且该列可以是时间戳,计数器或任何其他版本跟踪结构。但我仍然不明白如何确保WRITE完整性(意味着如果多个进程同时更新相同的实体,那么实体正确地反映它应该在的真实状态)。

I understand that optimistic locking involves the addition of a column for tracking the record's "version", and that this column can be a timestamp, a counter, or any other version-tracking construct. But I'm still not understanding how that ensures WRITE integrity (meaning that if multiple process are updating the same entity at the same time, that afterwards, the entity correctly reflects the true state it should be in).

有人可以提供一个具体的,易于理解的示例,说明如何在Java中使用乐观锁定(可能是MySQL数据库)。假设我们有一个 Person 实体:

Can someone provide a concrete, easy-to-understand example of how optimistic locking could be used in Java (against, perhaps, a MySQL DB). Let's say we have a Person entity:

public class Person {
    private String firstName;
    private String lastName;
    private int age;
    private Color favoriteColor;
}

Person 实例获得持久化到 MySQL表:

And that Person instances get persisted to a people MySQL table:

CREATE TABLE people (
    person_id PRIMARY KEY AUTO_INCREMENT,
    first_name VARCHAR(100) NOT NULL,
    last_name VARCHAR(100) NOT NULL,        # } I realize these column defs are not valid but this is just pseudo-code
    age INT NOT NULL,
    color_id FOREIGN KEY (colors) NOT NULL  # Say we also have a colors table and people has a 1:1 relationship with it
);

现在假设有2个软件系统,或1个系统有2个线程,同时更新相同的 Person 实体:

Now let's say there are 2 software systems, or 1 system with 2 threads on it, that are trying to update the same Person entity at the same time:


  • 软件/ 1正尝试保留姓氏变更(从

  • 软件/尝试持续更改喜爱的颜色(从

  • Software/Thread #1 is trying to persist a surname change (from "John Smith" to "John Doe")
  • Software/Thread #2 is trying to persist a change in the favorite color (from RED to GREEN)

  1. 如何实现乐观锁定和/或颜色表? (寻找特定的DDL示例)

  2. 然后如何在应用程序/ Java层使用这种乐观锁定? (寻找特定的代码示例)

  3. 有人可以让我通过一个场景,其中DDL /代码更改(从上面的#1和#2)将在我的场景其他情况),并且将乐观地锁定 / 表正确吗?基本上,我希望在操作中看到乐观锁定,并简单解释它为什么起作用。

  1. How could optimistic locking be implemented on the people and/or colors tables? (Looking for specific DDL example)
  2. How could you then utilize this optimistic locking at the application/Java layer? (Looking for specific code example)
  3. Can someone run me through a scenario where the DDL/code changes (from #1 and #2 above) would come into play in my scenario (or any other scenario) and would "optimistically lock" the people/colors tables correctly? Basically, I'm looking to see optimistic locking in action, with an easy-to-follow explanation of why it works.


推荐答案

通常,当你看到乐观锁定,你还使用一个库,如 Hibernate 或其他JPA实现与 @Version 支持。

Normally when you look into optimistic locking you also use a library like Hibernate or an other JPA-Implementation with @Version support.

this:

public class Person {
    private String firstName;
    private String lastName;
    private int age;
    private Color favoriteColor;
    @Version
    private Long version;
}

显然没有必要添加 @

while obviously there is no point of adding a @Version annotation if you are not using a framework which supports this.

这个DDL可以是

CREATE TABLE people (
    person_id PRIMARY KEY AUTO_INCREMENT,
    first_name VARCHAR(100) NOT NULL,
    last_name VARCHAR(100) NOT NULL,        # } I realize these column defs are not valid but this is just pseudo-code
    age INT NOT NULL,
    color_id FOREIGN KEY (colors) NOT NULL,  # Say we also have a colors table and people has a 1:1 relationship with it
    version BIGINT NOT NULL
);



版本会发生什么?



What happens with the version?


  1. 每次存储实体之前,都要检查数据库中存储的版本是否仍然是您所了解的版本。

  2. 如果是,版本增加一个

为了完成这两个步骤,而不冒其他进程改变两个步骤之间的数据的风​​险,它通常通过语句

To get both steps done without risking an other process changing data between both steps it is normally handled through a statement like

UPDATE Person SET lastName = 'married', version=2 WHERE person_id = 42 AND version = 1;

执行语句后,检查是否更新了行。如果你这样做,没有人改变了数据,因为你已经读了,否则有人改变了数据。如果其他人更改了数据,您通常会收到 <$ c $

After executing the statement you check if you updated a row or not. If you did, nobody else changed the data since you've read it, otherwise somebody else changed the data. If somebody else changed the data you will normally receive an OptimisticLockException by the library you are using.

此异常应导致所有更改被撤销,更改过程作为实体被更新的条件重新启动的值可能不再适用。

This exception should cause all changes to be revoked and the process of changing the value to be restarted as the condition upon which the entity was to be updated may no longer be applicable.

所以没有冲突:


  1. 进程A读取人

  2. 进程A写入人从而增加版本


  3. 处理B写人,从而增加版本

  1. Process A reads Person
  2. Process A writes Person thereby incrementing version
  3. Process B reads Person
  4. Process B writes Person thereby incrementing version

冲突:


  1. 进程A读取人

  2. 进程B读取人

  3. 增加版本

  4. 尝试保存为自从人读取后更改的版本时,进程B接收到异常

  1. Process A reads Person
  2. Process B reads Person
  3. Process A writes Person thereby incrementing version
  4. Process B receives an exception when trying to save as the version changed since Person was read

如果Color是另一个对象,您应该使用相同的方案放置一个版本。

If Colour is another object you should put a version there by the same scheme.


  • 乐观锁定是合并冲突更改的理想选择。乐观锁定将阻止进程意外覆盖另一个进程的更改。

  • 乐观锁定实际上不是真正的DB锁定。它只是通过比较版本列的值来工作。您不会阻止其他进程访问任何数据,因此请期待您获得 OptimisticLockException s

  • Optimistic Locking is no magic to merge conflicting changes. Optimistic Locking will just prevent processes from accidentally overwriting changes by another process.
  • Optimistic Locking actually is no real DB-Lock. It just works by comparing the value of the version column. You don't prevent other processes from accessing any data, so expect that you get OptimisticLockExceptions

如果许多不同的应用程序访问您的数据,最好使用数据库自​​动更新的列。例如for MySQL

If many different applications access your data you may be best off using a column automatically updated by the database. e.g. for MySQL

version TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

这样,实现乐观锁定的应用程序将注意到哑应用程序的更改。

this way the applications implementing optimistic locking will notice changes by dumb applications.

如果您更新实体的频率超过 TIMESTAMP 的解析度或Java解释,这种方法可能无法检测到某些更改。此外,如果让Java生成新的 TIMESTAMP ,您需要确保运行应用程序的所有计算机都处于完美的时间同步。

If you update entities more often than the resolution of TIMESTAMP or the Java-interpretation of it, ths approach can fail to detect certain changes. Also if you let Java generate the new TIMESTAMP you need to ensure that all machines running your applications are in perfect time-sync.

如果所有应用程序都可以改变,整数,长,...版本通常是一个很好的解决方案,因为它永远不会受到不同的设置时钟; - )

If all of your applications can be altered an integer, long, ... version is normally a good solution as it will never suffer from differently set clocks ;-)

还有其他情况。您可以使用散列或甚至在每次要更改行时随机生成 String 。重要的是,当任何进程保存数据进行本地处理或在缓存中时,不要重复值,因为该进程将无法通过查看版本列来检测更改。

There are other scenarios. You could e.g. use a hash or even randomly generate a String every time a row is to be changed. Important is, that you don't repeat values while any process is holding data for local processing or inside a cache as that process will not be able to detect change by looking at the version-column.

作为最后一种手段,您可以使用所有字段的值作为版本。虽然这在大多数情况下是最昂贵的方法,但它是一种获得类似结果而不改变表结构的方法。如果您使用Hibernate,则会出现 @OptimisticLocking - 注释以强制执行此行为。使用 @OptimisticLocking(type = OptimisticLockType.ALL)在实体类失败,如果任何行更改,因为你已经读取实体或 @OptimisticLocking type = OptimisticLockType.DIRTY),只是当另一个进程更改了您更改的字段时失败。

As a last resort you may use the value of all fields as version. While this will be the most expensive approach in most cases it is a way to get similar results without changing the table structure. If you use Hibernate there is the @OptimisticLocking-annotation to enforce this behavior. Use @OptimisticLocking(type = OptimisticLockType.ALL) on the entity-class to fail if any row changed since you have read the entity or @OptimisticLocking(type = OptimisticLockType.DIRTY) to just fail when another process changed the fields you changed, too.

这篇关于乐观锁定由具体(Java)示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆