What's the Hi/Lo algorithm?

前端 未结 5 1807
面向向阳花
面向向阳花 2020-11-22 06:00

What\'s the Hi/Lo algorithm?

I\'ve found this in the NHibernate documentation (it\'s one method to generate unique keys, section 5.1.4.2), but I haven\'t found a goo

5条回答
  •  遥遥无期
    2020-11-22 06:25

    Since this is a very common question, I wrote this article, on which this answer is based on.

    The hi/lo algorithms splits the sequences domain into “hi” groups. A “hi” value is assigned synchronously. Every “hi” group is given a maximum number of “lo” entries, that can by assigned off-line without worrying about concurrent duplicate entries.

    1. The “hi” token is assigned by the database, and two concurrent calls are guaranteed to see unique consecutive values
    2. Once a “hi” token is retrieved we only need the “incrementSize” (the number of “lo” entries)
    3. The identifiers range is given by the following formula:

      [(hi -1) * incrementSize) + 1, (hi * incrementSize) + 1)
      

      and the “lo” value will be in the range:

      [0, incrementSize)
      

      being applied from the start value of:

      [(hi -1) * incrementSize) + 1)
      
    4. When all “lo” values are used, a new “hi” value is fetched and the cycle continues

    You can find a more detailed explanation in this article:

    And this visual presentation is easy to follow as well:

    While hi/lo optimizer is fine for optimizing identifier generation, it doesn't play well with other systems inserting rows into our database, without knowing anything about our identifier strategy.

    Hibernate offers the pooled-lo optimizer, which offers the advantages of the hi/lo generator strategy while also providing interoperability with other 3rd-party clients that are not aware of this sequence allocation strategy.

    Being both efficient and interoperable with other systems, the pooled-lo optimizer is a much better candidate than the legacy hi/lo identifier strategy.

提交回复
热议问题