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?
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).
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.
Not thread safe. May return erroneous results if used between more than one threads.
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."
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.
If you need unique file names for temporary files, use File.createTempFile(prefix, suffix, directory).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With