Java / Scala多线程文件写入

Java / Scala multi thread file writing

我想要 运行 多个 Gatling 模拟,这将在一个文件中共享数据。

现在我有以下代码:

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 接收一个字符串并检查文件是否包含它。如果是,它将 returns 设置为 false,否则将字符串写入文件。 它非常适合模拟中的数百个虚拟用户,但不适用于并行 运行ning 模拟。我注意到在两个并行的 运行ning 模拟中,文件中写入了 230 行,其中 2 行是相同的。

当另一个 运行ning 模拟打开文件时,我如何设法锁定该文件?

谢谢, 维克多

如果"parallelly running simulations"你的意思是你正在执行多个模拟过程,那么问题是var available = true的值和synchronized上的锁在内存中space 每个进程,它们不共享。

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