Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is System.nanoTime() guaranteed to return unique values?

I have a multi-threaded Java program that creates hundreds of temporary files in seconds. The files are placed in /tmp and are named using System.nanoTime().

Are the file names guaranteed to be unique?

like image 409
Danny Choi Avatar asked Mar 19 '13 07:03

Danny Choi


People also ask

Is system nanoTime () reliable?

nanoTime() is a great function, but one thing it's not: accurate to the nanosecond. The accuracy of your measurement varies widely depending on your operation system, on your hardware and on your Java version. As a rule of thumb, you can expect microsecond resolution (and a lot better on some systems).

What does system nanoTime return?

nanoTime() method returns the current value of the most precise available system timer, in nanoseconds. The value returned represents nanoseconds since some fixed but arbitrary time (in the future, so values may be negative) and provides nanosecond precision, but not necessarily nanosecond accuracy.

Is system nanoTime thread safe?

Not thread safe. May return erroneous results if used between more than one threads.

Is nanoTime monotonic?

System. nanoTime should be monotonically increasing -- if you have two calls to it, A and B , and A happens-before B , then A <= B . But in practice, you can actually observe nanoTime going "backwards."


2 Answers

No, there is no guarantee that every call to System.nanoTime() will return a unique value.

Use File.createTempFile() or Files.createTempFile() instead. They are designed for just this purpose, and will generate unique file names for you.

like image 153
NPE Avatar answered Sep 29 '22 05:09

NPE


If you need unique file names for temporary files, use File.createTempFile(prefix, suffix, directory).

like image 43
Thilo Avatar answered Sep 29 '22 05:09

Thilo