Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I worry about leaking the "this" pointer in Swing?

Tags:

java

swing

I learned recently (in a class based on C#) that it's sometimes considered dangerous to register event listeners in an object's constructor, because those event listeners are given a reference to that object before the object is fully initialized, and could (at least in theory) attempt to access the object before construction is complete.

From what I understand, accessing an object before construction is complete can cause a crash, at least in some languages...if it doesn't cause a crash, then we would only care that the registration occur last, so our object is ready to receive events when we register its listeners.

I'm now starting on a new Swing GUI, and noticed that my standard practice when building Swing GUIs is to wire up the event listeners in the constructor.

It seems unlikely that the event listeners of Swing components would be called before the constructor is complete, as they presumably are not wired up until the component is added to a visible Swing container, which can only happen after construction.

So, is there a real reason to avoid that anti-pattern when working in Swing? And if so, what is the simplest way to go about it?

like image 203
Theodore Murdock Avatar asked Feb 07 '12 22:02

Theodore Murdock


1 Answers

As long as you assign your event listeners in the UI thread than you'll be fine.

like image 113
Paul Nikonowicz Avatar answered Oct 27 '22 01:10

Paul Nikonowicz