我试图减少下面代码使用的内存量。我想要它使用5-10 be的最大内存,但我不确定这是否可能。在启动时,它现在大约需要10,1MB,在Thread.sleep之后大约需要40 it。我尝试过使用不同的BufferedReader实现,但这似乎并没有改变什么。我不是最擅长java的,尤其擅长内存管理,所以我可能错过了一些非常愚蠢的东西。如果有人能给我一些关于改进内存管理代码的指导,那就太棒了!
package tsviewerscanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
public class TSViewerScanner {
static URL url;
public static void main(String[] args) {
System.out.println("Started");
while (true) {
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
try {
url = new URL("https://www.tsviewer.com/ts3viewer.php?ID=1040506");
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
try {
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
String WebContentStr = reader.lines().collect(Collectors.joining("\n"));
if (WebContentStr.toLowerCase().contains("error code: 2568") && WebContentStr.toLowerCase().contains("insufficient client permissions")) {
System.out.println("WebContentStr contains both strings");
} else {
System.out.println("Strings not found");
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}发布于 2016-08-31 05:17:38
此代码的主要内存利用率问题是,在检查字符串是否存在之前,整个响应将加载到内存中。
与其将整个流缓冲到一个大字符串中,您可以在读取每一行时检查它们,一旦选中,旧行就会被垃圾收集。
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
AtomicBoolean hasError = new AtomicBoolean();
AtomicBoolean hasInsufficentPermission = new AtomicBoolean();
reader.lines().map(String::toLowerCase).forEach(line-> {
if(line.contains("error code: 2568")) hasError.set(true);
if(line.contains("insufficient client permissions")) hasInsufficentPermission.set(true);
});
if (hasError.get() && hasInsufficentPermission.get()) {
System.out.println("WebContentStr contains both strings");
} else {
System.out.println("Strings not found");
}
}然而,我怀疑您所看到的行为更多的是与您误解JVM如何使用内存有关。
JVM使用的内存量更多地取决于分配了多少内存、程序运行了多长时间以及程序在运行过程中创建了多少垃圾。
JVM的内存使用量通常并不表示在任何给定时间堆应用程序需要多少内存。
可以通过多种方式调整JVM内存的使用,但这超出了这个答案的范围。
https://stackoverflow.com/questions/39239945
复制相似问题