generate random long user ID

Ulli Schmid picture Ulli Schmid · Feb 6, 2013 · Viewed 8.3k times · Source

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?

Answer

GeorgeVremescu picture GeorgeVremescu · Feb 6, 2013

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