У меня есть блок кода в scala, который считывает список файлов и выполняет предварительный анализ и записывает результат в выходной файл. Даже хотя, я закрываю свой файл должным образом после чтения и записи, я вижу, что моя память постоянно растет. Любая помощь будет оценена.Утечка памяти в scala
Update
Моя забота, если System.gc() неявно вызывается по истечении определенного периода времени (в идеале, когда моя программа работает из кучи пространства), моя скорость работы программы должно быть нормальным после Вызывается system.gc(). Но этого не происходит.
Вот мой код ->http://pastebin.com/q2g8kf2U Вот мой выход HPROF свалка (http://pastebin.com/PEH8yR3v)
This is my main function - Here, I call function hashMe, where I pass my number and insert it into my dictionary/map. Finally once this is done for all files in my input folder, I write it the dictionary. I can't find a memory leak here. But,my memory is growing continuously during the program run. Thanks for you help !
def hashFunction(switchFolder: java.io.File ,phoneFields: List[Int] ,codeFields : List[Int], delimiter: String,Ftype: Char){
var numFiles = 0;
var startT = new Date()
var switchType = switchFolder.getName
Logging(switchType,4)
Logging("Now start processing: " + switchFolder.getAbsolutePath + " at Time: " + startT.toString)
implicit def closingSource(source: Source) = new {
val lines = source.getLines()
var isOpen = true
def closeAfterGetLines() = new Iterator[String] {
def hasNext = isOpen && hasNextAndCloseIfDone
def next() = {
val line = lines.next()
hasNextAndCloseIfDone
line
}
private def hasNextAndCloseIfDone = if (lines.hasNext) true else { source.close() ; isOpen = false ; false }
}
}
def gzInputStream(gzipFile: File) = new GZIPInputStream(new BufferedInputStream(new FileInputStream(gzipFile)))
def linesFromGzip(gzipFile: File): Iterator[String] = {
Source.fromInputStream(gzInputStream(gzipFile)).closeAfterGetLines()
}
def lines(filename: String) : Iterator[String] = {
scala.io.Source.fromFile(new File(filename)).getLines()
}
var switchDir: File = new File(outputDir + "/" + YM + "/" + switchType)
if(!switchDir.exists) { switchDir.mkdir() }
var fileList = (switchFolder).listFiles // DaysList
Logging("Processing collection (Non-Date Type) YM: "+ YM + " SwtichType: "+ switchType)
Logging("Number of files to be processed :" + fileList.length)
for(file <- fileList) // For each file
{
var fileName = file.getName.substring(0,file.getName.lastIndexOf('.'))
numFiles = numFiles + 1
var result = linesFromGzip(file).map(_.split("\\" + delimiter,-10)).map(line => line.map{var index =0 ; word => index = index + 1 ; if(word == "") word
else if(phoneFields.contains(index-1)) {
var phNo = new PhoneNumber(word,'P');
phNo.hashMe(phNo.number);
}
else if (codeFields.contains(index-1)) {
var imsiCode = new PhoneNumber(word,'C');
imsiCode.hashMe(imsiCode.number);
}
else word}).map(line => line.mkString(delimiter))
var fw = new FileWriter(outputDir + "/" + YM + "/" + switchType + "/" + fileName);
var bw = new BufferedWriter(fw);
for(x <- result){ bw.write(x +"\n");}
bw.close();
fw.close();
} // End for
Logging("Finished " + switchType + " collection")
} // End try
catch {
case ioe: java.io.FileNotFoundException => { Logging("File Error ! Check",2);}
case aie: java.lang.ArrayIndexOutOfBoundsException => { val msg = "!!! Exception: Index Out of Bound Error"; Logging(msg,2);}
case e: Exception => { var msg = "General Exception.Check!" ; println(msg); Logging(msg,2); }
}
var endT = new Date()
Logging("Total Number of files in " + switchType + " is: " + numFiles)
Logging("Total TimeTaken: " + ((endT.getTime() - startT.getTime())/1000).toInt + " Seconds")
} // hashFunction
Отправьте свой код здесь. Мы не собираемся удалять местоположение, которое может стать недействительным позже/ – hexafraction
Можете ли вы уточнить, что вы спрашиваете в своем обновлении? Ваша программа замедляется с течением времени и остается медленной даже после того, как сработали кучи? Можете ли вы опубликовать минимальный пример кода с показателями, которые показывают это? Если вы имеете дело с большими файлами, убедитесь, что вы не занимаете место подкачки. – thesamet