简体   繁体   English

如何解决内存泄漏?

[英]How can I fix my memory leak?

I made this small script to ping google.pt and do something with the ping result. 我制作了这个小脚本来ping google.pt,并对ping结果执行一些操作。 The problem is that if I let the script run for a while, it uses more and more RAM. 问题是,如果让脚本运行一段时间,它将使用越来越多的RAM。

I can't seem to find the mistake, can you help me? 我似乎找不到错误,您能帮我吗?

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);
    }


}

EDIT: the getPingValue method: 编辑: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;
}

and the take actionFromPingValueMethod just calls this on a jframe that I created: 而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();

}

the ping command normally runs forever and thus your condition ping命令通常永远运行,因此您的情况

while ((inputLine = in.readLine()) != null) 

only will be false when your timeout (specified with -t ) triggers. 仅在超时(由-t指定)触发时为false。 You should limit the number of ping request by using the -c count parameter. 您应该使用-c count参数限制ping请求的-c count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM