memory leak in GUI event handlers – swing^c#

Here’s a common java swing memory leak as described on stack overflow — Essentially, because you register an object as a listener and forget to unregister, the notifier ends up holding onto the reference of the object, and leaks a bit of memory.

Same problem with c# events. [[effective c#]] refers to it as “runtime coupling despite compile-time loose coupling”. Recall an event
is a pseudo field in a class, and the fields’ type is a delegate, which is a list of 2-pointer constructs. First pointer usually points to a listener object. Imagine a bunch of large listener objects are added to the delegate’s inv list (registered for event), and one of them is no longer needed. You want its memory freed, but the event source object still holds a reference via the delegate instance. See [[effective c#]] item 23. One tip is to unregister in the listener’s Dispose()

I feel the dotnet event/delegate language construct has no exact java counterpart at the language level, but at runtime, swing event
paradigm == c# event paradigm. Fundamentally the same paradigm. Part of the paradigm is that the event source object holds a
collection of subscriber Objects. If the GUI stays up for 22 hours then the subscriber Objects are held “hostage” for that long, and
cannot be garbage collected.

swing box layout – hearsay

To overcome the first Box layout confusions, Let’s start with Y-axis layout – top-down insertion of JComponents.  (X-axis alignment would mean left-to-right insertion).

Each JComponent calls myComponent.setAlignmentX() in Y-axis layout. Note the X vs Y. They must be that way. This is a bit confusing. Here’s my explanation — Top-down insertion means inserting a new component underneath the last component, but if new component is tiny shall we push it to the left or to the right? The new component must specify “Put me to left” or “Put me to the right”.

setAlignmentX(Component.RIGHT_ALIGNMENT) actually uses a float constant == 1.0. In fact, all setAlignmentX/Y methods take a float input. 0.5 always means center. LEFT_ALIGNMENT (== 0.0) means “push me to far Left”.

(Now hold your breath — in X-axis layout, 0.0 means “push me to the top”. This confused the hell out of me initially.)

The above is the box layout behavior when all components in the layout share the Same alignment number (be it 0.5, 1.0 or whatever). The behavior is completely different when the alignment numbers are non-uniform.

Popular combinations —
— right-justified:
new BoxLayout(…, Y_AXIS);

— centered:
new BoxLayout(…, Y_AXIS);

never edit table model on non-EDT?

A Swing interviewer asked me

Q: Can a non-EDT thread ever writes to the underlying data-structure of a (table/tree/list) model? 
A: If it does, we are at risk. EDT could be reading it — uncoordinated and unexpected. EDT might see corrupted data. Classic reader/writer race scenario. Murphy’s Law — if it could happen it will.

(In theory, EDT can also update the data due to a message listener or a DB operation –writer/writer race, but) This one scenario alone is reason enough. All underlying data queried by EDT should Never be modified outside EDT.

In one real world live trading app though, some MOM listener threads do indeed update underlying data structure. When that happens, users are not allowed to trigger a refresh — we can disable some buttons. After the update, we send invokeLater(fireXXX()) to refresh the view.

You may want to lock-protect the underlying data, but then EDT might be blocked. Yet, this is widespread. Look at DefaultTableModel in which EDT does access the underlying Vector, which is lock-protected. If the Vector is large, growing it (perhaps 2 folds) can take log(N) time, and EDT would be blocked for that duration. However, in practice this latency is probably below 50ms and unnoticeable.

As a minimum requirement, ALL models need to be thread-safe. That often entails locking or CAS or copy-on-write.

Swing models normally do not use large data structures (since a screen can’t realistically show even 1000 rows). If it does, update should ideally be designed with a worker thread, to populate a replacement data structure, and then ask EDT to swap it in. Many non-ideal situations exist in practice, which calls for specific techniques and tactical solutions.

tabbing policy – swing


The policy of a Swing application is determined by LayoutFocusTraversalPolicy. You can set a focus traversal policy on any Container by using the setFocusCycleRoot method.

Alternatively you can pass focus-traversal-policy-providers to the FocusTraversalPolicy() methods instead of focus cycle roots. 

Use the isFocusTraversalPolicyProvider() method to determine whether a Container is a focus-traversal-policy-provider. Use the setFocusTraversalPolicyProvider() method to set a container for providing focus traversal policy.

GUI (wpf/swing..) design is more OO

Background: “non-GUI” can mean anything — including but not limited to web, database-centric, MOM, workflow, number-crunching, data transfer/transformation gateway, market-data-driven … To avoid over-generalization and to provide some concrete focus, I’d say let’s look at telecom/business systems. This blog post is about my general observation that GUI systems are “more inherently” object-oriented.

But why bother? Well, if anyone is learning any OO design pattern, the best example is often found in GUI space. GUI architects use more OO design principles than in non-GUI. A serious GUI OO design should. If you want to improve on an OO design for a GUI app, or if you start from scratch, use OO design patterns liberally.

Here are my observations as to why GUI design is more inherently object-oriented —

#1) main characters — there are relatively few objects as Models, ViewModels, Views, timers, singleton collections… Mostly stateful, singleton domain entities. OO design pattern is most useful in such a context.
** transient objects —- In most non-GUI systems most objects are transient (as revealed by a profiler). In GUI, quite a few objects — not just the jcomponents, listeners and events — have well-defined life cycles from creation to destruction. Can you say the same about non-GUI apps? In non-GUI, there are rather few long-living domain objects.
** Domain objects —- (More than in non-GUI apps) majority of classes in a GUI system including the main characters and numerous non-visual objects map nicely into domain objects. This is a boon to OO designers, with profound consequences. OO analysis is more worthwhile, more natural and more justified.
** ownership – in GUI an object is often “owned” by another in a strict sense. Given the “main characters”, ownership is often well-defined.
** complex interaction – there’s more inter-object cooperation and interaction in GUI systems. In some methods, you easily identify some of the “main characters”.

– necessity —- In many non-GUI projects, sometimes you can make do without OO. OO is more necessary (and natural) to GUI projects. I think GUI developers often grow into serious OO designers.
– state — visual components (often singletons) are first-class objects in the purest sense. Each visual object needs a supporting cast of other objects such as the Model or ViewModel objects. They all have a large number of well-defined states (properties).
– modular —- OO is at its best if you need to divide up a big project into modules each for a different developer. Large GUI projects often have natural demarcations and well-defined modular interfaces. Non-GUI large OO projects have a few clear demarcations + many more unclear demarcations.
– Reusable component —- GUI system can use/create many reusable components. Plug-n-play.
** EJB were hyped as shrink-wrapped commercial components but I don’t think they are. GUI components are the best example of commercial reusable OO components.

– actors —- are more prevalent in GUI Entity-Relation design. GUI OO design includes a real “actor”, and long-living domain objects associated with the actors. Other OO designs seldom have one. Web site is a different story — the domain objects related to a “session” are often short-lived.
– asynchronous, message driven —- such systems are more amicable to OO modelling, partly because each sender/receive maintains its own state.
– Sequence diagram —- useful to event-driven GUI.
– STA —- A fundamental reason why GUI systems use “Single-Threaded Apartments” is the long-living domain objects. Need to protect their “consistency”
– Encapsulation —- (and Object State) Most important GUI objects have well-defined, often with standardized stateful fields. Not so in non-GUI.
– abstract interfaces —- many classes must support the same “interface”. We often need to treat the a bunch of Types the same way. This calls for interfaces.
– Inheritance
– Design patterns —- map nicely to GUI OO, more nicely than non-GUI OO. See for a list of design patterns in Swing