Java/Scala多线程文件写入

问题描述:

我想运行多个Gatling模拟,它将共享文件中的数据。Java/Scala多线程文件写入

现在我有以下代码:

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接收一个字符串并检查文件包含与否。如果是,则返回false,否则将字符串写入文件。 它可以在模拟中完美适用于数百个虚拟用户,但不适用于并行运行的模拟。我注意到在两个并行运行的模拟中,230行被写入文件中,其中2个是相同的。

我怎样才能设法锁定文件,而其他正在运行的模拟打开?

谢谢 尤

如果“平行运行模拟”你的意思是你在执行多个仿真流程,那么问题是,var available = true价值和对​​锁定在内存空间每个进程的内容并不共享。

如果是这种情况,您需要更改方法acquire()以锁定所有正在运行的进程共享的内容,例如,使用数据库上的锁定表或检查是否存在指示该资源的文件被锁住了。