我正在运行一个简单的扫描程序来解析一个字符串,但是我发现如果经常调用我会得到 OutOfMemory 错误。这段代码被称为为字符串数组重复构建的对象的构造函数的一部分:
编辑:这是更多信息的构造函数;关于扫描仪的尝试捕获之外没有更多的事情发生
public Header(String headerText) {
char[] charArr;
charArr = headerText.toCharArray();
// Check that all characters are printable characters
if (charArr.length > 0 && !commonMethods.isPrint(charArr)) {
throw new IllegalArgumentException(headerText);
}
// Check for header suffix
Scanner sc = new Scanner(headerText);
MatchResult res;
try {
sc.findInLine("(\\D*[a-zA-Z]+)(\\d*)(\\D*)");
res = sc.match();
} finally {
sc.close();
}
if (res.group(1) == null || res.group(1).isEmpty()) {
throw new IllegalArgumentException("Missing header keyword found"); // Empty header to store
} else {
mnemonic = res.group(1).toLowerCase(); // Store header
}
if (res.group(2) == null || res.group(2).isEmpty()) {
suffix = -1;
} else {
try {
suffix = Integer.parseInt(res.group(2)); // Store suffix if it exists
} catch (NumberFormatException e) {
throw new NumberFormatException(headerText);
}
}
if (res.group(3) == null || res.group(3).isEmpty()) {
isQuery= false;
} else {
if (res.group(3).equals("?")) {
isQuery = true;
} else {
throw new IllegalArgumentException(headerText);
}
}
// If command was of the form *ABC, reject suffixes and prefixes
if (mnemonic.contains("*")
&& suffix != -1) {
throw new IllegalArgumentException(headerText);
}
}
分析器内存快照显示了 Scanner.findInLine() 的 read(Char) 方法在操作期间分配大量内存,因为我扫描了几十万个字符串;几秒钟后,它已经分配了超过 38MB。
我认为在构造函数中使用它之后在扫描仪上调用 close() 会将旧对象标记为由 GC 清除,但不知何故它仍然存在,并且 read 方法在填充堆之前累积了千兆字节的数据。
谁能指出我正确的方向?