2

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:

  • should not use database sequence.
  • should not store anything in filesystem.
  • Sequence can be repeated across the day.
  • Sequence should not get repeated within the day, even if there's a JVM restart (this is already ensured with different attribute).
  • No of sequence per second is min requirement 99.

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.

2
  • 2
    The only way I can see to do this is to have one method generate sequence numbers based on the system clock, and every application has to get the sequence number from this one method. Commented Oct 30, 2020 at 10:43
  • @MohamedSaligh Is it an option to use a UUID? Commented Oct 30, 2020 at 17:23

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.