Having one puzzling requirement.
Basically I need to create unique id with these criteria
- 9 digits number, unique for the day (means it’s ok if the number appears again the next day )
- generated in realtime ; java only ( means no sequence number generation from database -actually no database access at all )
- the number is generated to populate a requestID, and around 1.000.000 id will be generated per day.
- UUID or UID should not be used ( more than 9 digits )
Here is my consideration :
- using sequence number sounds good, but in case JVM restart, the
requestId might be re-generated. - using time HHmmssSSS ( Hour Minute Second Milliseconds ) have 2 issues :
a. System Hour might be changed by server admin.
b. Can cause issue
if 2 requests being asked on same milliseconds.
Any idea?
Nine digits to handle 1,000,000 IDs gives us three digits to play with (we need the other six for the 0-999999 for the ID).
I assume you have a multi-server setup. Assign each server a three-digit server ID, and then you can allocate unique ID values within each server without worrying about overlap between them. It can just be an ever-increasing value in memory, except to survive JVM restarts, we need to echo the most recently allocated value to disk (well, to anywhere you want to store it — local disk, memcache, whatever).
To ensure you don’t hit the overhead of file/whatever I/O on each request, you allocate the IDs in blocks, echoing the endpoint of the block back to the storage.
So it ends up being:
In pseudocode:
…but again, that’s pseudocode, and you might want to throw some proactive stuff in there so you never block on I/O waiting for an ID when you need one.
The above is written assuming you already have some kind of application-wide singleton, and the
IDAllocatorinstance would just be a data member in that single instance. If not, you could readily make the above a singleton instead, by giving it the classicgetInstancemethod and having it read its configuration from the environment rather than receiving it as arguments to the constructor.