内存泄漏在哪里? [英] Where is memory leak?
问题描述
我使用InetAddress来解析IP地址,但是如果IP不可用,现在需要存储主机名.所以我介绍了一个班级主持人.
I used InetAddress to parse IP addresses, but now there is a need to store hostname if IP is unavailable. So I introduced a class Host.
case class Host(name:String, ip:InetAddress) {
import Host.{addressToBytes, compareSeqs}
override def toString:String = if (ip!=null) {ip.getHostName} else {name}
}
object Host {
implicit def stringToPattern(s:String): Pattern = Pattern.compile(s)
val separators = Seq[Pattern]("\\.", ":")
def separatedStrToBytes(s:String, separator:Pattern): Array[Byte] = {
val fields = separator.split(s)
var rv = new Array[Byte](fields.length);
fields.map(_.toInt.toByte).copyToArray(rv, 0)
rv
}
implicit def strToBytes(s:String): Array[Byte] = {
for (sep <- separators)
if (sep.matcher(s).find())
return separatedStrToBytes(s, sep)
null
}
implicit def strToHost(s:String):Host = {
var name = s
var ip:InetAddress = null
try {
val bytes = strToBytes(s)
if (bytes != null) {
ip = InetAddress.getByAddress(bytes)
// println( "parsed ip: "+s)
}
} catch {
case e:UnknownHostException =>
}
if (ip==null) {
ip = InetAddress.getByName(s)
}
new Host(name, ip)
}
}
进行此更改后,我的软件开始失败,并出现了分隔的StrToBytes中的"java.lang.OutOfMemoryError:超出了GC开销限制".我在这里是否犯了任何内存处理错误?
With this change my software started to fail with "java.lang.OutOfMemoryError: GC overhead limit exceeded" in separatedStrToBytes. Have I made any memory handling mistakes here?
我感谢您对设计的任何评论.由于需要Array [Byte]作为InetAddress.getByAddress参数,因此无法缩短解析时间.目标平台具有Scala 2.7.7.
I appreciate any comments on design. I was unable to make parsing shorter due to need of Array[Byte] as InetAddress.getByAddress argument. Target platform has Scala 2.7.7.
编辑:我已将虚拟分析替换为虚拟模型,发现我的程序稍后在其他地方仍无法解析几兆字节的数据.用Pattern.split(s:String)和预编译的模式每次替换String.split(s:String)都会使其运行时间稍长.那不能解决我的问题,但是这个问题现在可能已经解决.我仍然需要设计注释.
EDIT: I've replaced parsing with dummies and found out that my program still fails a few megabytes of parsed data later elsewhere. Each replacement String.split(s:String) with Pattern.split(s:String) and precompiled pattern makes it run slightly longer. That doesn't solve my problem, but this question may be closed now. I still need design comments though.
推荐答案
您的代码在2.8.0上运行良好(您应该考虑迁移到它,因为它已经是最终的并且相当稳定)-没有检测到OutOfMemory.
Your code runs just fine against 2.8.0 (you should consider migrating to it, as it's already final and quite stable) - no OutOfMemory detected.
您要进行的一些优化:
implicit def strToBytes(s:String)= (for {separator <- separators find(_.matcher(s).find)} yield separatedStrToBytes(s, separator)) getOrElse null
implicit def separatedStrToBytes(s:String, separator:Pattern) = s split separator.pattern map(Integer.parseInt(_).toByte)
scala> import Host._
import Host._
scala> strToBytes("127.0.0.1")
res9: Array[Byte] = Array(127, 0, 0, 1)
这篇关于内存泄漏在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!