I am working on a game "loot" element (Swing JComponent
), that would disappear if out of frame bounds for a long (I've set 1 sec in example to let you check if faster) time. This option works fine, but...
If I remove one from JFrame
, it is not finalized. (Another resource leak!)
Loot is Runnable
. I have the following code in the run()
method that is used to create a new Thread (new Thread(loot).start();
):
class Loot extends JComponent implements Runnable{
static JFrame frame=new JFrame(){
public void remove(Component c){super.remove(c);revalidate();}
};
int lifetime=100;
public Loot(){
frame.add(this);
frame.setVisible(true);
new Thread(this).start();
}
public void run(){
while(lifetime>0){
if(outOfFrameBounds())lifetime--;else lifetime=100;
//movement processing
try{Thread.sleep(10);}catch(InterruptedException ex){}
}
setVisible(false);
frame.remove(this);
System.gc();
System.runFinalization();
}
public boolean outOfFrameBounds(){
return true;//check if it's out of bounds
}
public void finalize(){System.out.println("loot removed");}
public static void main(String[]args){
new Loot();
}}
output (even after System.gc()
call):
When the cycle ends, I need to delete the loot
.
Can the finished anonimous Thread
prevent discarding the loot object?
Or is the main problem caused by some frame reference that left after removing component from it?
Why can not garbage collector destroy loot
?
And the main question is **"How can I make my programm here to destroy the loot object, call finalize() and, as a consequence, print "loot removed\n".