Search code examples
javafiletimetemporary-files

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?


Solution

  • 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.