Posts in Category "Troubleshooting and FAQ"

Catching UncaughtError in Flex Modules

A common issue amongst those building Flex Applications that use Flex Modules is that the UncaughtError capability of Flash Player 10.1 does not work for Modules. This is due to the fact that Modules dereference the module SWF’s loaderInfo right away, in order to make unloading modules automatic. In other words, as soon as you dereference the last instance of classes in the module, the SWF can be garbage collected. If Flex did not dereference the loaderInfo, the developer would have to keep track of what instances of module classes have been created and whether they are still around, and only if they are all gone would you dereference the loaderInfo.

It turns out that the UncaughtError mechanism relies on having loaderInfo references so the module subsystem in currently incompatible with UncaughtErrors. The Flash Player engineers are testing out a fix where the main application becomes the fallback for any UncaughtErrors that have not been caught and cancelled. For now, though, I figured out a way to hook directly to the module’s loaderInfo and listen to UncaughtErrorEvents there. That will allow you to get UncaughtErrors from the module. The key is in the timing. By the time the ModuleEvent.READY fires, it is too late, the loaderInfo has been dereferenced and is null. During ProgressEvents, the loaderInfo may not be available. But fortunately, at the time of ModuleEvent.SETUP, you can grab the loaderInfo and listen for UncaughtErrorEvents.

Here are some relevant snippets of code. Let’s say you have an application with an UncaughtErrorEvent handler like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:fx=""


private function init():void

private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
trace("caught uncaught error");


<!-- Place non-visual elements (e.g., services, value objects) here -->

<mx:ModuleLoader id="moduleLoader" url="GEHFlexModule.swf" width="200" height="150" />

In this app, the uncaughtErrorHandler will get UncaughtErrors from every other point of the application except for the module loaded by the ModuleLoader. To get the UncaughtErrors from the module, all you have to do is add a ModuleEvent.SETUP event handler:

<mx:ModuleLoader id="moduleLoader" url="GEHFlexModule.swf" width="200" height="150" setup="setup(event)" />

and use the setup event to hook up the uncaughtErrorHandler to UncaughtErrors from the module.

private function setup(event:ModuleEvent):void

Hope that helps.

Migratory Foul: Performance Problems Migrating From Flex 3.x To Flex 4.x

Some folks migrating 3.x projects to 4.x have run into noticeable
performance degradation, especially if they are using the default skins that
ship with each SDK. This article attempts to explain why and propose
alternative implementations.

The main reason for the difference is that the the default skins/theme for
4.x is Spark and the default skins/theme for 3.x is Halo. Spark skins are
simply not as fast as the Halo skins. The Halo skins are written as highly
optimized ActionScript and are based on a lightweight Flex class called
ProgrammaticSkin. And partly because of those optimizations, the way you
would write or modify a skin for a MX Button could be drastically different
than the way you’d write a skin for MX DataGrid or MX ComboBox.

In Spark, we wanted a consistent approach to writing every skin. And we
wanted interoperability with the MX components. For reasons like that, the
Spark skins are based on a Skin class that in turn is based on UIComponent.
That instantly makes your skin heavier and slower than a Halo skin. Then,
we wanted every skin to be written in MXML so that the tools can more easily
understand the parts of the skin and assist in the modification and
development of a skin. Most folks know that MXML tends to be slower than
ActionScript, but we chose MXML to enable non-programming designers to be
involved in the skinning workflow without those designers having to worry
about mucking up a bunch of ActionScript code.

The cost per-skin of this extra weight is on the order of a few milliseconds
per skin, but it adds up. A recent test case was putting 250 checkboxes on
the screen. A somewhat unrealistic case since it is hard to cram 250
checkboxes on a screen and make it usable, but it took another 500ms in the
debugger player so the developer noticed right away when he went from 3.x
with Halo to 4.x with Spark. Even if the goal was 100 checkboxes, the extra
200ms would cause some animation to freeze noticeably.

Now, if you are migrating a 3.x project for which you have already written
your own custom theme based on ProgrammaticSkin and you are going to use the
same theme in 4.x, you shouldn’t see problems of this magnitude. It really
has only been an issue when you were using the Halo theme and you now try to
use an MXML-based theme like Spark. So what should you do? Consider not
using MXML-based themes for now. We are looking at ways to optimize an
MXML-based skin hopefully in time for our 2012 releases so hopefully this is
just a short-term issue. We must admit, though, that it is enough of an
issue that the mobile theme for the new mobile components in Flex 4.5 are
written in ActionScript and not in MXML, and that’s why we’re working on
MXML skin performance post-Flex 4.5.

You have choices: You can only swap in ActionScript-based skins for a few
components, or swap in a whole theme. Just replacing the Spark MXML
checkbox skin with the Halo checkbox skin (but leaving the Application and
other skins as MXML-based Spark skins) made a huge difference in performance
since the majority of work was in those 250 checkbox skins that were being

Another new capability of Flex 4.x that can cause noticeable performance
degradation when compared to a 3.x application is what we call Advanced CSS.
In Flex 4 we support more CSS selector types but they require more
processing and less caching. If you create enough components in one chunk,
you might notice the extra time spent. We are looking at optimizations
post-Flex 4.5 as well. You can turn off Advanced CSS by setting the
compiler’s compatibility-version flag to 3, but that turns off lots of other
things as well and makes it harder to incrementally add or swap in Spark

It is possible to subclass components and turn off Advanced CSS
for entire classes of components. The following link shows how I turned off
Advanced CSS in a subclass of CheckBox.
Download Sample Source

In analyzing these test cases, it became apparent that the “natural” way to
build up display object “trees” in ActionScript is not the most optimal in
terms of performance. Lots of folks dynamically create dialogs and other
sub-sections of their UI via code like this:

var loginUI:VBox = new VBox();
var loginText:TextInput = new TextInput();
var loginButton:Button = new Button();

It turns out this is terribly inefficient compared to this almost identical

var loginUI:VBox = new VBox();
var loginText:TextInput = new TextInput();
var loginButton:Button = new Button();

All I did was addChild the outer container before adding its children. In
other words, it is faster to parent the parent before parenting the
children. Why? Because the CSS style calculations that involve inheriting
styles cannot be calculated until you have a parent. So in the first
example, when adding the TextInput and Button to the Vbox, a bunch of
temporary work gets done that gets tossed and re-done when the Vbox is
finally added to the child. If you use the second pattern, the CSS style
calculations don’t have to do any temporary, throw-away, work. It turns out
if you look at the code generated for an MXML file, you’ll see that parents
are parented before parenting their children. In the 250 checkbox cases,
the code was using the first pattern. By changing it to the second pattern
(and using the Halo theme) the test case on 4.x actually runs faster than
the 3.x test case. Yes, if the same optimization had been done on the 3.x
test case then 3.x would still be faster, but there is less degradation for
the second pattern because that is the common MXML-generated path and some
work was done to optimize it. Another new feature of 4.x is per-module
styles and the overhead of that capability (which had the main benefit of
greatly reducing probability that modules will get stuck in memory) carries
less penalty if you parent the parent first.

Remember that the underlying Flash Player is a deferred renderer. Adding an
empty Vbox to the app first won’t cause it to show up on the screen until
the rest of the code finishes running so there is no danger of flicker or
other visual artifacts.

In conclusion, if you are seeing performance degradation when migrating from
3.x to 4.x, and it is related to these topics in this article, then it was a
decided trade-off we made to involve designers in the development process
and produce better user experiences, or provide more CSS capabilities, or
reduce the chance memory leaks. But you can choose to use ActionScript
skins, do some subclassing to turn off Advanced CSS on components that are
created often, and build your dynamic UI more optimally and reduce the
degradation or in some cases, get even better performance than what you had
experienced in 3.x.

Flex and Embedded Fonts

Flex tries to provide you with the most flexible way of using embedded fonts in your applications. If your application consists of just one SWF and you embed fonts in that SWF, everything should just work, but once there are multiple SWFs involved, while it should work most of the time, if it doesn’t, you may need the following information to figure out why. With Flex 4 defaulting to using RSLs, your default configuration now involves multiple SWFs and many more of you are suddenly using multiple-SWF applications because each RSL counts as a SWF.
The principle rule is that there are two places that the Flash Player will look to find an embedded font to use to display text in a TextField or TextLine. It will look in the global table where fonts are registered via Font.registerFont, and it will look in the SWF whose code instantiated the TextField or TextLine.
Font.registerFont has a couple of limitations. One is that, if two SWFs try to register the same font, the last one in wins. That is normally ok until you start embedding font subsets (only certain characters in the font) which you might want to do when optimizing for SWF size, especially with large Asian fonts. If SWF A has only upper case characters and SWF B has only lower case characters, for example, then SWF A won’t be able to display its characters if SWF B loads later and registers its font of lower case characters.
The second limitation is that there is no Font.unregisterFont call so registering a Font pins the SWF with the font in memory.
For those reasons, Flex never tries to call Font.registerFont. Instead it has an infrastructure that tries to make sure that all TextFields and TextLines are created by code in the SWF that contains the embedded font. We use the term “SWF context” to mean the SWF whose code created the TextField or TextLine. And because a TextField or TextLine can have only one SWF context, it means that all fonts displayed in a TextField or TextLine must be embedded in the same SWF. If you must mix, you will have to register the font and deal with the fact that the SWFs containing the fonts may never unload.
Making sure the right code instantiates TextField is a bit trickier than it first seems. You can’t just put calls to “new TextField” or “TextBlock.createTextLine()” in a single factory class and link that class into every SWF. The ApplicationDomain rules may cause the class in a SWF to be ignored (see the modules presentation on the blog for details).
For example, suppose I create a TextLineFactory class and link it into SWF A and SWF B. If SWF A loads SWF B, when B calls TextLineFactory, it will be calling the one in SWF A and thus the TextLine will be created in a different SWF context than B expected and the embedded fonts won’t show up. Or suppose the TextLineFactory class is in an RSL. Then it is not in SWF A or SWF B so those SWFs won’t be able to display text using fonts embedded in those SWFs.
In order to solve this, Flex adds code to a uniquely named class in every SWF it generates for RSLs and Applications and Modules. That way there are no ApplicationDomain class collisions. Flex does that by adding that code to the main class of every SWF and names it after the SWF. For example, if you have A.SWF with mx:Application, Flex wraps the mx:Application with a SystemManager subclass called something like A_SystemManager and adds factory APIs to that subclass.
For TextField, Flex uses the ISystemManager.create() method. For TextLine, Flex uses the ISWFContext.callInContext API. If you are writing your own text-based components, it would be a good idea to subclass the Flex components so you can inherit the embedded font infrastructure that makes those calls and also figures out the next hard part: given an embedded font, which SWF do you reference to call these APIs? Again, because of ApplicationDomain rules, any class you write may be running in a different SWF context from the caller.
Flex tracks all fonts it embeds in SWFs and each SWF registers its embedded fonts in the EmbeddedFontRegistry on load. (Yes, we do it in a way that allows the SWF to unload). When a Flex text component is about to display text, it looks up the fontFamily, fontStyle and fontWeight and sees if there is an embedded font in the registry that matches, biasing the search to the current SWF so that colliding subsets will work. The EmbeddedFontRegistry returns the best SWF context for that font and the component uses that SWF context to create the TextField or TextLines. That means that even simple components like Label will destroy and create a new children if the font styles change since the style change could require the use of a different SWF context.
How can Flex always know which SWF is the current SWF given the ApplicationDomain rules? This is done in Flex by conditionally propagating the moduleFactory property to child components. All top-level components in a SWF have their moduleFactory set to the SWF’s IModuleFactory and propagate it to children unless the child already has a moduleFactory set.
Note that even though SystemManager is an IModuleFactory, not all ISystemManagers are IModuleFactory like AIR’s WindowedSystemManager so code should not assume that you can determine your SWF context from the systemManager property.
There are lots of implications from having this infrastructure. If you can’t control the code that creates the TextLine or TextField because the instances are created via mx.core.IFactory (itemRenderers and Chart visuals), you may need to use ContextualClassFactory or code up something similar. It also means you can’t cache a single TextField for measuring text; you may have to cache a TextField in each SWF context. It means that SystemManager.isFontEmbedded and Font.enumerateFonts may not know about every font that has been loaded and return inaccurate results.
And, it turns out that other font-related APIs must also be called in the correct SWF context. If you call ElementFormat.getFontMetrics(), you must also call that via ISWFContext if you are using embedded fonts in a multi-SWF configuration. Getting this wrong an result in really subtle bugs like having the position of strikethrough and underline being off by a pixel or two, or having baselinePosition be off by a pixel or two.
The Flex team has put a lot of work into making all of this transparent to developers, so hopefully you won’t ever need to know all of this, but folks definitely get tripped up by this now and then. And now, if you do, I hope you can use the information in this post to solve your problem.

What We Know About Unloading Modules

As of this writing, the Flex team does not know of any scenario that pins a module in memory forever assuming the developer has cleaned up all references.
If you have a module that does not unload, the steps to diagnose the problem are:
1) Make sure the module is being loaded into a child applicationDomain (use default parameters for the load() method in most cases)
2) Use the profiler to make sure there are no references to objects in the module. The most common causes of leaks are:

a. Styles. Even without any mx:Styles tag in your MXML, if a module uses a component that is not used by the main application, the module will register the default styles for that component with the StyleManager and pin the first instance of the module. You can use the -compiler.keep-generated-actionscript compiler option to see which default styles the module and main application are using. You can use the -compiler.keep-all-type-selectors compiler option on the main application to force the main application to register the default styles for every component in the defaults.css file. Prior recommendations to load style declarations via runtime CSS (StyleManager.loadStyleDeclarations) are withdrawn. Runtime CSS modules register styles in a different way so they can be unloaded and will not prevent this problem.
b. Resources. If a module uses components that use ResourceBundles that are not used by the main application, those resource bundles will get registered with the ResourceManager and pin the first instance of the module. You can use the -compiler.keep-generated-actionscript compiler option to see which resource bundles the module and main application are using. You can force the main application to have those additional resource bundles by adding the resource bundle metadata to the main application. For example, to add the “controls” resource bundle, you would add to the main application MXML file: [ResourceBundle(“controls”)] If you are loading your resource bundles as modules, make sure the resource modules have completed loading before loading the module that is being pinned.
c. ExternalInterface.addCallback. Modules should not use ExternalInterface.addCallback. That registers the method with the browser and there is no way to unregister it at this time. The recommended practice is to have the main application register a method that will call a function reference and put the module’s method in that function reference, then set the function reference to null when the module unloads.
d. Timers and other timer mechanisms. The use of Timer, setTimeout(), and setInterval() can cause leaks. Timer’s must be stopped and have their listeners removed, setTimeout and setInterval must be paired with calls to clearTimeout() and clearInterval().
e. Listeners to events from objects outside of the module. Use weak references or make sure to remove the event listeners. Remember, when you call a.addEventListener(“foo”, b.someMethod), it is ‘a’ that has a reference to ‘b’, not the other way. If you are listening to a parent or stage or singleton, those objects now have a reference to the object that whose method is going to get called and can cause leaks.
f. Focus. If an object in the module has focus, the FocusManager will still have a reference to the module. A good UI will move focus to some other object outside the module before removing the module.
g. RemoteObject. If a module brings in a data class that is going to be part of a server query, that class can get registered with the Player and result in a reference to the module. Link data classes into the main application when possible.
h. Loaded Images. If a module loads an image, that image must be unloaded otherwise the player will still keep some data buffers around.

3) Once there are no references to objects in the module, the Flash Player can still keep a module in memory for a while if objects in the module ever had focus. Other activity in the application, such as typing and clicking will eventually release references to the module and the module will be freed from memory. Try typing and clicking in the main application or another module and see if the pinned module gets garbage-collected.
4) Debug-versions of a module on the Debugger Player can also lead to a module being stuck in memory. Debug-versions contain debug information that can get registered with the debugger and not released. The final test is always to use release versions of the modules and application on a release version of the player.
A word (or 50) about unloadAndStop(): UnloadAndStop is a new API in player 10. It is intended to stop audio and video playback and the timeline, but does not claim to deference all references to classes in a loaded SWF and has not been proven to help modules free themselves from memory. While it may help child applications loaded via SWFLoader, it is not used by modules. Modules actually call Loader.unload() on themselves immediately upon completion of loading so that they will be available for garbage collection once all references to objects in the module have been removed. This is because a module can be used to make multiple instances of the various classes in the module and we don’t want to add the overhead of tracking all of those instances or require that a developer have some other way of tracking when all references to a module have been removed so they could know when to call unload().

More on Finding Memory Leaks

It seems that the most common scenarios involving memory leaks are the ones involving loading and unloading multiple SWFs like modules and sub-applications. Every day, we learn more and more about how the player manages memory and its other idiosyncracies, so it is time for another summary.
When debugging suspected memory leaks when loading/unloading SWFs, I generally do the following:
1) Set up the app or a test harness to load and unload the SWF multiple times (at least 3) and force a garbage collection pass after each unload or unload, then use the profiler to see how many copies of the module’s xxx_FlexModuleFactory or the subapplication’s xxx_SystemManager are in memory. If more than 1, keep loading and unloading and see if that number continues to grow. Any module or SWF that introduces a new component with styles will register those styles with the StyleManager and stick around forever the first time it loads. You can prevent that from happening by pre-loading the styles in the main app or via a CSS module. A second copy might stay around if it was the last thing loaded because the player or FocusManager might still be hanging onto it. If you see more than 2, that’s definitely a leak and you should use the profiler to find the leak.
2) After several loads and unloads, I take a memory snapshot, then do more loads and unloads and take another snapshot. I clear all filters, remove percentages, sort by class name and compare manually the number of instances of every class. They should match exactly, except maybe for a few Strings and sometimes, WeakReference. Everything else is suspect and deserves investigation.
3) Once I think I got all references to the SWF cleaned up, I next run several loads and unloads in the debugger and check the console. I am looking for lines in the debug output that start with:
That tells me that the player thought everything was cleaned up and unloaded the SWF. Note that it may not say that right away, even after GC requests as sometimes the player has internal references to a SWF that get cleaned up “later”. If I don’t see that, I go back to step 2 and compare memory snapshots looking for other things that might be leaking
4) Now that I’m convinced that even the player thinks it is ok to unload the SWF, if System.totalMemory is still increasing, the final test is to export release builds for all swfs and run them in a release player. The debugger player seems to hang onto debug information in the SWFs and can skew System.totalMemory. In recent tests, once I get past step 3, the release player’s reporting of System.totalMemory is much more acceptable, capping at a much smaller and acceptable maximum memory value.
5) Once you get past that, some of you might still see memory attributed to the player still growing when using OS tools to examine the player process. That remains an open area of investigation by the player team. For Internet Explorer, one often finds that minimizing IE causes its claim on memory to shrink, implying that it is something to do with IE’s memory management and not the Flash Player or your application. We don’t know of any way to programatically force IE to give up that memory. We also have seen reports of other browsers reporting memory growth even though Flash thinks things should be unloaded. If you can reproduce that in a small test case, file bugs with those test cases.

Debugging Tricks

FlexBuilder 3 Beta 2 no longer makes both release and debug versions on every build, in order to speed up build times. This means that the debug version is no longer suffixed with -debug and it appears more than one of you used that to turn on debugging functionality w/o changing your code.
Also, a few folks have asked for a single line of code that could be pasted verbatim into function bodies that would report the name of the function, and a few others have wondered if there is a way to get the name of the calling function.
Assuming you are using a debugger player, the source code at this link demonstrates how to do each of these things. See setDebugFlag(), getFunctionName() and getCallingFunctionName().
Download file

private function setDebugFlag():void
var e:Error = new Error();
var s:String = e.getStackTrace();
// trace(s);
var i:int = s.indexOf("setDebugFlag");
if (s.charAt(i + 14) == '[')
debugMode = true;
public var debugMode:Boolean = false;
private function getFunctionName(e:Error):String
var s:String = e.getStackTrace();
var i:int = s.indexOf("at ");
var j:int = s.indexOf("()");
return s.substring(i + 3, j);
private function getCallingFunctionName(e:Error):String
var s:String = e.getStackTrace();
// trace(s);
var i:int = s.indexOf("at ");
i = s.indexOf("at ", i + 3);
if (i == -1)
return "caller unknown";
var j:int = s.indexOf("()", i + 3);
return s.substring(i + 3, j);

where the latter two functions are can be used like this:

private function doSomething():void
trace(getFunctionName(new Error()));
private function doSomethingElse():void
trace(getFunctionName(new Error()));
private function doit():void
trace(getFunctionName(new Error()));
trace("   called by", getCallingFunctionName(new Error()));

Usual caveats apply, and the numbers and strings might have to be adjusted for different languages.

SWF is not a loadable Module

Did you get this error using modules? This error means that you tried to load the module from a different server than the one the loader is running on, and/or you don’t have crossdomain.xml permission to load the module from that server.
Flash/Flex has a lot of security built in so that mean people can’t use Flash/Flex to do mean things to other servers. All SWFs therefore belong to the domain of the server where that SWF lives.
For example, if we’re running a SWF that lives at, that SWF belongs to the domain “”. If you try to load a SWF from somewhere else, such as or, then you are loading across domains.
The Flash Player will then look in the root directory of or for a file called crossdomain.xml, and see if is listed in that file (or the file lists ‘*” which means “everybody”). If not, you cannot load the SWF as a module because, due to other security restrictions in the Flash Player, SWF loaded from another domain without crossdomain.xml permission go in a separate SecurityDomain, which means that it will have its own ApplicationDomain which means it cannot share classes with the main SWF and thus the ModuleManager can’t see the objects in the SWF as Modules.
Because this is a security-related issue, there are no real workarounds. You either have to make sure that your modules are in the same domain as the SWFs that load them, or you have to set up crossdomain.xml files so they can be used from SWFs in other domains. If you are trying to use a third-party module, you probably don’t have access to the third-party’s server and thus can’t add yourself as an accepted domain in their crossdomain.xml file. That’s annoying, but those are the rules. Server owners must either give explicit permission or decide to openly share SWFs resources on a server by listing your domain in crossdomain.xml or using ‘*”.

ArrayCollection, Arrays and Server Data

I call this the “array of one” problem. I make a request to the server for some data, usually a list of things, and it comes back and I stuff it in a dataprovider and it displays just fine….sometimes. Sometimes I get an error about converting/coercing ObjectProxy into an Array or ArrayCollection. After further investigation it turns out that it is only if the list of things has zero or one items that I get the error.
This is an unfortunate fact-of-life when serializing objects as xml. XML is really just formatted text, so all type information is essentially lost. We don’t know if the data is a String, Number, Array or Object and end up making a good guess.
For example, if I have the following data to send:
class Employee
var Name:String = “Alex”;
var EmployeeID:Number = 123;
It gets serialized as a one string
On the receiving side, the code sees that there isn’t anything numeric about “Alex” so it leaves it as a string, and that “123” is all digits so it parses it as a Number.
Now if the data is a list of values such as
class Manager
var Manager:String = “Steve”;
var DirectReportEmployeeIDs:Array = [123, 456, 789];
That might get serialized as:
On the receiving side, the code sees that there are multiple so it decides to make an Array of those values.
Now if there is only one direct report, the data is going to come over as:
and sure enough, it no longer looks like an array, does it? That’s why this is the “array of one” problem.
So, how to deal with it? There is no single right answer. There are type-preserving serialization technologies but they aren’t as popular. You can just check to see if the thing you think is an Array or ArrayCollection is, and if not, convert it to an array by pushing onto a new array, or you can work with the data as XML and use XMLListCollection which will see the “array of one” as an XMLList.
To check, you would add code like:
if (event.result is ObjectProxy)
list.dataProvider = [ event.result ]; // short cut for new array()
list.dataProvider = event.result.
To use XML and XMLListCollection, set the resultFormat=”e4x”.