storia321
storia321

Reputation: 381

Any algorithm/logic to generate 6 digit alphanumeric unique identifier in a multi process setup

I have a use case where I need to generate 6 digit alphanumeric unique identifier. Have come across many solution but all seems to be fail in a multi processor environment and also might generate same unique identifier at some point of time.

Is there any solution/algorithm to generate 6 digit alphanumeric unique identifiers at run time in a multi processor environment and should generate unique identifier always.

Upvotes: 2

Views: 2799

Answers (3)

David Soroko
David Soroko

Reputation: 9096

Have you considered commons-id ? You may be interested in some variant of UUID version 1, The standard UUIDs provided are 128 bit long though.

Upvotes: 0

OldCurmudgeon
OldCurmudgeon

Reputation: 65859

A simple sequence of numbers starting at 0 and increasing by 1 would generate a non-repeating sequence (obviously stopping at the end or when you exceed 6 digits). Generate the number in base 36 and it is alpha-numeric.

To make that accessable concurrently you merely need to put the sequence generator in a Runnable and run it in a thread that feeds a BlockingQueue. You can then pull numbers off the queue in a thread-safe fashion. Something like this:

class SafeSequence implements Runnable {

    // My current value.
    long i = 0;
    // Use BlockingQueue to assist cuncurrency.
    BlockingQueue<Long> q = new ArrayBlockingQueue<>(10);

    String get() throws InterruptedException {
        // Format at take time.
        return Long.toString(q.take(), 36);
    }

    @Override
    public void run() {
        try {
            while (true) {
                // Always runs in it's own thread so no concurrency issues.
                q.put(i++);
            }
        } catch (InterruptedException ie) {
            // Just drops out of the loop on iterruption.
        }
    }

}

If you don't want sequential you could use an LFSR to generate the sequence.

Upvotes: 1

Dima
Dima

Reputation: 40510

Six alphanumeric characters is way too few for a guaranteed globally unique I'd. If that's your requirement, your best bet is, probably, to keep a counter in a global variable, return base64 - encoded value as the next I'd when needed, and increase the counter atomically.

If you need this to work across different machines, out the counter into a database (sequence). You can assigned ranges to each server, to avoid making a db query every time a new I'd is generated.

Upvotes: 1

Related Questions