3

I want to use the result of System.currentTimeMillis() in the multithreaded appplication to generate unique IDs. This is my code:

    class MyRunnableClass implements Runnable{
        @Override
        public void run() {
            long thisValueShouldBeUnique = System.currentTimeMillis ();
        }
    }

I start 10 threads which run MyRunnableClass object run() method. Is it true, that sometimes the result of System.currentTimeMillis () in different threads may be the same?

Benas
  • 2,106
  • 2
  • 39
  • 66

2 Answers2

6

The function System.currentTimeMillis() returns the current time in milliseconds. So if your threads run during the same millisecond, yes this function will return the same result. So you can generate UUIDs like that: UUID.randomUUID()

Creart
  • 146
  • 1
  • 10
3

Today's CPUs can process around 100,000,000,000 instructions per second, so the answer is definitely "Yes, It is true that sometimes the result of System.currentTimeMillis() in different threads may be the same".

Yoav Gur
  • 1,366
  • 9
  • 15