此代碼是否會導致內存泄漏?這會造成內存泄漏嗎?
何時啓動垃圾回收器?定時器結束時是否?或GC將被調用,即使計時器仍在運行?
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類:查詢
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();
}
}
方法數據庫:每當JVM覺得有必要這麼做
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;
}
}
}
Java GC基於* object reachability而工作* - 任何從根不可達的對象(例如,靜態成員,當前堆棧中的局部變量等)都有資格被回收。回收實際發生的時間和方式取決於GC。 – user2246674 2013-05-14 00:57:55
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等 – user2246674 2013-05-14 01:00:02
這裏觀察到的問題究竟是什麼?它看起來像連接的生命週期可能沒有適當的限制,但.. – user2246674 2013-05-14 01:08:36