I knows to make sync when writing to a file easily, but the problem is when there are multiple files, we to make sync on per file. I have write some code like this to make people easily to understand what i have said
import java.io._
import java.util.concurrent.{ConcurrentHashMap, ConcurrentMap}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
object Main {
val lock: ConcurrentMap[String, Boolean] = new ConcurrentHashMap[String, Boolean]()
def writeToFile(path: String): Unit = {
while (lock.get(path)) {}
lock.put(path, true)
println("write to file " + path)
Thread.sleep(2000)
lock.remove(path)
}
def main(args: Array[String]): Unit = {
Future {
writeToFile("1")
}
Future {
writeToFile("1")
}
Future {
writeToFile("1")
}
while (true) {}
}
}
The result will be:
write to file 1 [sleep 2 seconds]
write to file 1
write to file 1
The last two lines print at the same time. There are any another solution, please tell me :) thanks!!!