How to fix memory leak in java

I am currently trying to write a program that receives a striped json object from steam and uses that object to determine if I can buy an item on steam or not.

This works, however I seem to be getting massive memory leaks and I have no idea how to fix this as I am a beginner programmer. Here is the code:

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;


public class SteamMarketAlert {

    @SuppressWarnings("unused")
    private JAlertWindow alert;
    private URL jsonUrl;
    private float walletValue;
    private boolean itemBuyable;

    public SteamMarketAlert(URL itemUrl, float walletValue)
    {
        this.itemBuyable = false;
        this.jsonUrl = getJSONurl(itemUrl);
        this.walletValue = walletValue;
    }

    private URL getJSONurl(URL itemUrl)
    {
        String jsonString = itemUrl.toString();

        String firstPart = jsonString.substring(0, jsonString.indexOf("market/") + "market/".length());

        String appid = jsonString.split("/")[5];
        String marketHashName = jsonString.split("/")[6];

        String secondPart = "priceoverview/?currency=2&appid=" + appid + "&market_hash_name=" + marketHashName;

        try {
            return new URL(firstPart + secondPart);
        } catch (MalformedURLException e) {
            System.err.println("Failed to create json url");
            return null;
        }

    }

    public void checkMarket()
    {
        Thread thread = new Thread(){
            @Override
            public void run(){
                try {
                    while(!itemBuyable)
                    {
                        sleep(5000);                        
                        if(isBuyable(getPagehtml()))
                            itemBuyable = true;
                    }
                    alert = new JAlertWindow();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }   
        };

        thread.start();


    }

    private boolean isBuyable(String pagehtml)
    {
        int firstIndex = pagehtml.indexOf(";") +1;


        float marketValue = Float.parseFloat(pagehtml.substring(firstIndex, firstIndex + pagehtml.substring(firstIndex, pagehtml.length()).indexOf("\"")));

        return (marketValue <= walletValue)? true:false;
    }

    private String getPagehtml(){

        try(Scanner scanner = new Scanner(jsonUrl.openConnection().getInputStream())) {

            scanner.useDelimiter("\\Z");
            return scanner.next();
        } catch (IOException e) {               
            e.printStackTrace();
            return null;
        }

    }

    public static void main(String[] args)
    {
        try {
            float walletValue =  82.64f;
            URL itemUrl = new     URL("http://steamcommunity.com/market/listings/730/StatTrak%E2%84%A2%20P90%20%7C%20Asiimov%20%28Factory%20New%29");
            SteamMarketAlert sma = new SteamMarketAlert(itemUrl,walletValue);
            sma.checkMarket();


        } catch (MalformedURLException e) {

            e.printStackTrace();
        }

    }
}

      

I have narrowed down the problem to the checkMarket () method. However, I cannot figure out what is going on. Could you please point out how I can fix this (and maybe point out any flaws in my code). Note that the JAlertWindow object simply displays the JFrame with "CAN BUY" on it - nothing special.

edit: I have updated the code since posting and users informed me that try-with-resource blocks exist. Thanks to everyone who helped me understand how java garbage collection works. :)

+3


source to share


3 answers


This is probably not a memory leak in Java until you get an OutOfMemoryException or see persistent garbage collection.



Using 18MB in 10 minutes doesn't seem like a memory leak, this is how Java works. If you really want to make sure you can turn on verbose GC and see how often it collects, but I don't think you have a real problem.

0


source


You are fetching html pages and because of this some objects (String etc.) have to be allocated in memory on every get. Later (when they are no longer used) these objects will be deleted and the memory is marked as GC.



Sorry for the rather simplistic explanation. if you want to know more, just read about java GC, heap structure, etc.

0


source


Why not start a Java profiler? I recommend using YourKit . I use it a lot to find the cause of the memory leaks I have on my servers. It's great for connecting and uninstalling apps; you have to play with it.

Here's a link to my own video on how to find a memory leak; Link

If you need more help you should quickly read their docs

-4


source







All Articles