Mohamed Saligh
Mohamed Saligh

Reputation: 12339

Java Sequence Generation without repetition

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

Answers (1)

Nowhere Man
Nowhere Man

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

Related Questions