简体   繁体   中英

How can I fix my memory leak?

I made this small script to ping google.pt and do something with the ping result. The problem is that if I let the script run for a while, it uses more and more 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:

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:

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

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

only will be false when your timeout (specified with -t ) triggers. You should limit the number of ping request by using the -c count parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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