[英]How can I fix my memory leak?
我制作了這個小腳本來ping google.pt,並對ping結果執行一些操作。 問題是,如果讓腳本運行一段時間,它將使用越來越多的RAM。
我似乎找不到錯誤,您能幫我嗎?
public static void main(String[] args) {
String ip = "google.pt -t -4";
int pingRetrieved = 0;
//window that displays the ping
s = new Square();
String pingCmd = "ping " + ip;
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec(pingCmd);
BufferedReader in = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
//System.out.println(inputLine);
pingRetrieved = getPingValueFromPingResult(inputLine);
takeActionFromPingValue(pingRetrieved);
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
編輯:getPingValue方法:
private static int getPingValueFromPingResult(String inputLine) {
String[] splitString;
String timeParameter;
if (inputLine.contains("Reply")) {
splitString = inputLine.split(" ");
timeParameter = splitString[4];
timeParameter = (timeParameter.split("="))[1];
timeParameter = timeParameter.replace("ms", "");
return Integer.parseInt(timeParameter);
}
return 0;
}
而take actionFromPingValueMethod只是在我創建的jframe上調用此方法:
public void printNumber(int ping){
this.getContentPane().removeAll();
JLabel jl = new JLabel();
Font f;
if(ping == 0){
this.setLocation((int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth()-200), 0);
jl = new JLabel("Connection Error");
f = new Font("Fixedsys", Font.PLAIN, 25);
}else{
this.setLocation((int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth()-100), 0);
jl = new JLabel(ping+"ms");
f = new Font("Fixedsys", Font.PLAIN, 25);
}
jl.setFont(f);
jl.setForeground(Color.MAGENTA);
this.getContentPane().add(jl, java.awt.BorderLayout.NORTH);
this.pack();
}
ping
命令通常永遠運行,因此您的情況
while ((inputLine = in.readLine()) != null)
僅在超時(由-t
指定)觸發時為false。 您應該使用-c count
參數限制ping請求的-c count
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.