16

I have a class that needs to write to a file to interface with some legacy C++ application. Since it will be instantiated several times in a concurrent manner, it is a good idea to give the file an unique name.

I could use System.currentTimemili or hashcode, but there exists the possibility of collisions. Another solution is to put a var field inside a companion object.

As an example, the code below shows one such class with the last solution, but I am not sure it is the best way to do it (at least it seems thread-safe):

case class Test(id:Int, data: Seq[Double]) {
    //several methods writing files...
}

object Test {
  var counter = 0

  def new_Test(data: Seq[Double]) = {
    counter += 1
    new Test(counter, data)
  }
}

2 Answers2

33

Did you try this :

def uuid = java.util.UUID.randomUUID.toString

See UUID javadoc, and also How unique is UUID? for a discussion of uniqueness guarantee.

Eric Pohl
  • 2,324
  • 1
  • 21
  • 31
Gregosaurus
  • 591
  • 4
  • 5
  • I've looked at that, but it seems to be not guaranteed to be unique. –  Feb 05 '14 at 18:40
8

it is a good idea to give the file an unique name

Since all you want is a file, not id, the best solution is to create a file with unique name, not a class with unique id.

You could use File.createTempFile:

val uniqFile = File.createTempFile("myFile", ".txt", "/home/user/my_dir")

Vladimir Matveev mentioned that there is a better solution in Java 7 and later - Paths.createTempFile:

val uniqPath = Paths.createTempFile(Paths.get("/home/user/my_dir"), "myFile", ".txt"),
Community
  • 1
  • 1
senia
  • 37,745
  • 4
  • 88
  • 129
  • 1
    Or, even better, [`Paths.createTempFile(Paths.get("/home/user/my_dir"), "myFile", ".txt")`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempFile(java.nio.file.Path,%20java.lang.String,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...)), if you're using Java 7 and later. – Vladimir Matveev Feb 05 '14 at 17:29
  • Why you write here `Paths.createTempFile`, shouldn't it be `Files.createTempFile` ? – Dfr May 30 '14 at 15:41