Reputation: 23
I'd like to run multiple Gatling simulations which would share data in a file.
Right now I have the following code:
import java.io.BufferedWriter
import java.io.File
import java.io.FileNotFoundException
import java.io.FileWriter
import java.io.IOException
import java.util.Scanner
import scala.collection.mutable.ListBuffer
class AppIDLocker(fileName:String) {
var available = true
def acquire() = synchronized {
while (!available) wait()
available = false
}
def release() = synchronized {
available = true
notify()
}
def TestAndUse(id:String):Boolean = {
acquire()
var list = new ListBuffer[String]()
try {
val file = new File(fileName)
try {
val scanner = new Scanner(file)
while(scanner.hasNextLine()) {
list += scanner.nextLine()
}
scanner.close()
} catch {
case e: IOException => println("Had an IOException trying to read the file for AppIdLocker")
}
try {
val fw = new FileWriter(file, true)
val bw = new BufferedWriter(fw)
if (list.contains(id)) {
release()
return false //the ID has been used by an other Officer already
}
else{
bw.write(id + "\n")
bw.flush()
bw.close()
release()
return true //the ID is appended, and ready to be used by the Officer, who called the method
}
} catch {
case e: IOException => println("Had an IOException trying to write the file for AppIdLocker")
return false
}
} catch {
case e: FileNotFoundException => println("Couldn't find file for AppIDLocker.")
return false
}
}
}
TestAndUse receives a string and checks if the file contains it or not. If yes, it returns with false, else it writes the string to the file. It works perfectly for hundreds of virtual users in a simulation, but not for parallelly running simulations. I noticed that in two parallelly running simulation 230 lines were written in the file and 2 of them were the same.
How could I manage to lock the file while it's opened by the other running simulation?
Thank you, Viktor
Upvotes: 0
Views: 361
Reputation: 1854
If by "parallelly running simulations" you mean that you are executing multiple simulation processes, then the problem is that the value of var available = true
and the lock on the synchronized
are in the memory space of each process and they are not shared.
If this is the case you need to change the method acquire()
to lock on something that is shared by all the running processes, for example using a lock table on a database or checking the presence of a file that indicates that the resource is locked.
Upvotes: 2