0

Is it ok to set actions like in the code sample below? Are there any possible garbage collection problems that might be caused by this? And if not what would be the best way to do this?

btnAwesomeButton=new JButton(new AbstractAction("Awesome Button") {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        //Do stuff here
        //Refer to the components on parent windows through ParentWindowClass.this.componentName      
    }

});
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
m0s
  • 4,250
  • 9
  • 41
  • 64

3 Answers3

3

This is a very common idiom. There are no garbage collection issues, provided you don't stash a reference to the AbstractAction subclass instance somewhere (like a hash table) where it will persist after actionPerformed returns.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
2

Yes, it's perfectly normal. This is what we call anonymous inner class. There is no garbage collection with this issue at all.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
2

Yes, there are potential gotchas in garbage collection with this. However, the other answers are correct in that it is a standard idiom.

When you create an anonymous inner class like this it has a hidden reference to the outer class. That means that as long as this button exists with that action, the outer class will still be referenced, as with everything that that outer class references.

This is typically not a problem in practice, however, since the outer class will usually be the window or panel where this button resides, and the button will be around as long the panel is. That is why it is the standard idiom - it is typically fine.

Yishai
  • 90,445
  • 31
  • 189
  • 263
  • Your analysis is correct, but its not really a gotcha. More like saying you can have bugs if you program. – Justin Mar 30 '11 at 18:50