1

Will this code causes a memory leak?

When will the garbage collector be activated? Is it when the timer finishes? or GC will be called even though the timer is still running?

public static SwingWorker sw;

t2 = new Timer (300,this);
     t2.start();

@Override
public void actionPerformed(ActionEvent arg0) {
try {
    sw = new TextAreaMainPanelWorker();
    sw.execute();
} catch (Throwable e) {
    e.printStackTrace();
}   
}

TextAreaMainPanelWorker class:

public class TextAreaMainPanelWorker extends SwingWorker<Integer, Integer>
{

protected Integer doInBackground() throws Exception
{
    ConnectMysql.fetchMessage(MainPanel.jtep,MainPanel.sd,MainPanel.count);
    return 1;
}

protected void done()
{
    try
    {
        ConnectMysql.rodolfol(MainPanel.jtep, MainPanel.sd);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

Method for query to database:

public static void fetchMessage(JTextPane jtep,StyledDocument sd,int count  )
{
    try{

    String query = "SELECT members.username, message,color FROM chat JOIN members ON chat.user_id = members.id WHERE message_id > "+count+" AND user_id != 1";
    ps = con.prepareStatement(query);
    rs = ps.executeQuery();
    }catch(Exception e){}
}

public static void rodolfol(JTextPane jtep,StyledDocument sd){
    try {
        while(rs.next())
        {
            try {
                final JLabel jp = new JLabel(rs.getString("username")+ "\n");
                jp.setAlignmentY(0.75f);
                final String usernameChat = rs.getString("username");
                jp.addMouseListener(new MouseListener(){

                    @Override
                    public void mouseClicked(MouseEvent e) {}

                    @Override
                    public void mouseEntered(MouseEvent e) {
                        Cursor c = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
                        jp.setCursor(c);
                    }

                    @Override
                    public void mouseExited(MouseEvent e) {
                    }

                    @Override
                    public void mousePressed(MouseEvent e) {
                        if(SwingUtilities.isRightMouseButton(e)){System.out.print("lawl");}
                        if(e.getClickCount() == 2)new OneToOneChat(usernameChat);

                        jp.setForeground(Color.BLUE);
                    }

                    @Override
                    public void mouseReleased(MouseEvent e) {
                    jp.setForeground(Color.BLACK);
                    }
                });
                jp.setFont(new Font("arial",Font.BOLD,16));
                jtep.insertComponent(jp);
                StyleConstants.setForeground(MainPanel.sas2, Color.BLACK);
                MainPanel.sd.insertString(MainPanel.sd.getLength(), ": ", MainPanel.sas2);
                StyleConstants.setForeground(MainPanel.sas,new Color(Integer.parseInt(rs.getString("color"))));
                sd.insertString(sd.getLength(),rs.getString("message")+ "\n", MainPanel.sas);

            } catch (BadLocationException e1) {
            }finally{
            }
            MainPanel.count++;}
    } catch (SQLException e) {
    }finally{
    if (rs != null) {
            try {
                rs.close();
            } catch (SQLException sqlEx) { } 
            rs = null;
        }

    if (ps != null) {
            try {
                ps.close();
            } catch (SQLException sqlEx) { } 
            ps = null;
        }
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Dasda Sdasd
  • 73
  • 1
  • 9
  • Java GC works based off of *object reachability* - any object that is *not strongly reachable* from a root (e.g. a static member, a local variable in the current stack, etc) is eligible to be reclaimed. When and how the reclamation actually occurs are up to the GC. – user2246674 May 14 '13 at 00:57
  • http://stackoverflow.com/questions/5690309/garbage-collector-in-java-set-an-object-null , http://stackoverflow.com/questions/5667705/in-java-when-does-an-object-become-unreachable , http://stackoverflow.com/questions/2046761/what-is-object-graph-in-java , etc – user2246674 May 14 '13 at 01:00
  • What exactly is the observed problem here? It looks like the connection lifetime might not be appropriately bounded, but .. – user2246674 May 14 '13 at 01:08

2 Answers2

1

GC will be called whenever the JVM feels it is necessary to do so.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • so based on my code sw = new TextAreaMainPanelWorker(); sw will be garbage collected when sw will have a new reference? – Dasda Sdasd May 14 '13 at 01:00
  • I don't know how you inferred that from my answer. There can be 20 dangling references to it from previous runs before the JVM *"feels it is **necessary**"* (due to lack of memory) to run GC. – Andrew Thompson May 14 '13 at 01:02
  • 1
    @DasdaSdasd The object will become *eligible* for reclamation (assuming it is not otherwise strongly reachable). – user2246674 May 14 '13 at 01:03
1

When will the garbage collector be activated? Is it when the timer finishes? or GC will be called even though the timer is still running?

Garbage Collections will happen at any time, it feels like. Generally, when the application is running low on memory. GC may run when the timer is still running putting your application on pause (with Parallel/Throughput Collector).

So basically you have no control over when and the GC will kick in. It may happen at any time, regardless of what you are doing in your code.

goblinjuice
  • 3,184
  • 24
  • 26
  • will my codes causes aa memory leak cayse con connection will be open all time?? I read some articles about con not being closed and they say it will cause memory leak is it true based on my code? – Dasda Sdasd May 14 '13 at 01:05
  • It will not cause memory leak. Since Connection will be open for a long time, it will move to the Old Generation and will stay there as long as there are (strong) references to it. You may have "memory leaks" if you start adding Objects to a `HashMap` or another Collection and forget about them. Because they are referenced from `HashMap`, they will not get collected and hence Memory Leak. Hope this helps. – goblinjuice May 14 '13 at 01:08