2017-06-21 100 views
0

我想運行多個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個是相同的。

我怎樣才能設法鎖定文件,而其他正在運行的模擬打開?

謝謝 尤

回答

2

如果「平行運行模擬」你的意思是你在執行多個仿真流程,那麼問題是,var available = true價值和對​​鎖定在內存空間每個進程的內容並不共享。

如果是這種情況,您需要更改方法acquire()以鎖定所有正在運行的進程共享的內容,例如,使用數據庫上的鎖定表或檢查是否存在指示該資源的文件被鎖住了。