Do I need to free Swing components before letting them get garbage collected?

Wnen I use external resources such as files or DB connection I need to close them before I let them go.

Do I need to do the same thing with Swing components ? If yes then how ?


Normally, you don't need to dispose of objects when you are done with them (although setting the references to them to null may allow them to be GCed sooner). However, AWT and Swing objects allocate some amount of native resources that need to be freed. Furthermore, the AWT thread treats the windows as top-level objects, preventing them from being garbage collected and the JVM from terminating.

Thus, when you are done with your window, you need to dispose of it, which frees the native resources that it has allocated. One way to do this is to call Window.dispose() on it. However, a better option would be to call JFrame.setDefaultCloseOperation() when you initialize each of your root windows. If you pass it DISPOSE_ON_CLOSE it will take care of disposing itself when the user closes the window. When the last such window closes, the AWT thread will stop blocking and allow the JVM to close (assuming you don't have any other aberrant threads running). Alternatively, you can pass it EXIT_ON_CLOSE, which will cause your window to call System.exit(), which tells the JVM that your application is done and to gracefully terminate.

Need Your Help

iOS implement a long scroll view best practice

ios uitableview memory uiscrollview

Hi i would to implement a very long scroll view for a forum-like view, designing something similar to this image

How do you decide if a QA issue is a defect?

testing qa

I've worked for several companies as a developer and have recently moved into QA automation at a new company. Each company is different and I have yet to see a way of handling this that I really l...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.