Name
PK Block Generator Pattern
Goal
Efficiently generate a block of unique numerical identifiers, supporting distributed applications and eliminating risk of duplicate identifiers.
Participants
- Sequence block object
An object that provides unique primary keys to other objects upon request.
- Database sequence
A database feature that allows production of a series of unique identifiers.
Interactions
The application maintains an object responsible for handing out identifiers. The object maintains a block of identifiers and hands them out one at a time. When the current block is exhausted, the object accesses the database and reads a new unique value from a database sequence. The new value is used as a seed to generate a new block of sequences.
Notes
Since the database maintains the seed values used to generate each sequence block, there is no problem with duplicate identifiers, even if the application is running across multiple JVMs. The worst that will happen in this case is that identifiers may not be contiguous and may be assigned out of order.
Get J2EE Design Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.