Pergunta

I am writing an android app giving each client a long user ID through this formula:

long userID = (long) (Math.random() * 2 * Long.MAX_VALUE - Long.MAX_VALUE);

Am I utilizing MAX_VALUE correctly i.e. taking advantage of every possible long value?

What are my chances of having two duplicate user IDs with 10k, 100k or 1m users? How could I calculate this?

Foi útil?

Solução

You can make use of either one of those mentioned below:

  1. Instead of using the random to get a long user id, use current date and time expressed in milliseconds.

  2. Use a Random UUID

Outras dicas

https://github.com/bigfatsea/SUID Simple Unique Identifier

You may expect duplicated ids on same instance 136 years later, good enough for medium-small projects.

Example:

long id = SUID.id().get();

You can generate a Random UUID using randomUUID()

documentation

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top