Reputation: 12339
I have a specific requirement to generate a unique sequence number for the day. The utility should be able to generate the sequence without repeating even if there's a JVM restart.
Prerequisites:
Sequence format: ######## (8 digits max)
Note: this will be running in different instance of nodes and hence first digits of sequence is reserved for identifying the node.
Upvotes: 2
Views: 489
Reputation: 19545
A simple clock-based solution may look like this:
static int seq(int nodeId) {
int val = nodeId * 100_000_000 + (int) (System.currentTimeMillis() % 100_000_000);
try {
Thread.sleep(1); // introduce delay to ensure the generated values are unique
} catch (InterruptedException e) {}
return val;
}
The delay may be randomized additionally (up to 5 millis):
static Random random = new SecureRandom();
static int seq(int nodeId) {
int val = nodeId * 100_000_000 + (int) (System.currentTimeMillis() % 100_000_000);
try {
Thread.sleep(1 + random.nextInt(4));
} catch (InterruptedException e) {}
return val;
}
Upvotes: 2