How do I fix a memory leak in java

James

I'm currently trying to write a program that get a stringified json object from steam and uses the object to determine if I can buy an item on the steam market or not.

It works, however I seem to be getting massive memory leaks and I have no idea how to solve this problem as I'm 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've narrowed the problem down to the checkMarket() method. However, I can't seem to figure out what is going on. Can you please point out how I can fix this (and possibly point out all the flaws in my code), Note the JAlertWindow object just displays a JFrame with "CAN BUY" on it - nothing special.

edit: I updated the code since posting and users informed me that try-with-resource blocks existed. Thank you to everyone who has helped me understand how java garbage collection works. :)!

AngerClown

It's provbably not a memory leak in Java until you get an OutOfMemoryException or you see constant garbage collection.

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I fix this memory leak with an overloaded operator?

How do I fix this memory leak in my resize array method?

How can I fix to avoid a memory leak?

How can I fix this memory leak with char*?

In an interview I was asked how do you detect memory leak in Java?

Java memory mystery (do I have a leak)?

How do I fix a "memory leak of type 'wxPyXmlSubclassFactory *', no destructor found" error from wxPython/wxFormBuilder?

How do I fix this memory leak monitor func to avoid maximum call stack loop?

How can I create a memory leak in Java?

JNA Memory Leak - How to fix?

How to fix ‘memory leak’ in C

How can I fix the DependencyPropertyDescriptor AddValueChanged Memory Leak on AttachedBehavior?

How do I avoid memory leak when closing a QWebView?

Memory leak for static declaration of context and INSTANCE , how do I alter it?

Why does this Swift code leak memory, and how do I handle it?

How do I prevent memory leak from SolidColorBrush object?

How do I get rid of this memory leak in Haskell?

how do i copy a pointer to avoid a memory leak when operating on it?

How do i deal with this memory leak in this C 90 code?

How to fix memory leak with linked list?

How to fix memory leak in Next JS?

How to fix memory leak from an MQTT app?

how to fix memory leak in setTimeout closure?

Memory leak in Swift structures - How to fix this?

Memory leak / not properly freeing. How to fix?

memory leak in c++ and how to fix it

How do i fix it in Java

How to create a memory leak in Java?

How to find a Java Memory Leak