Plugging Video & Image Memory Leaks in Adobe Air

Adobe AIR is known for memory leak issues, especially in regards to loading and unloading video. I have seen applications with alternating video and images crash unexpectedly after running for only 20 minutes with no user input. After doing some investigating on my own, I can confirm what others have said in the past: You have to take extra steps when unloading a video or image, or risk a serious memory leak.

Removing Images: Clear the “source” attribute
Let’s say you want to unload a set of images from display object myContainer. The obvious solution would be to myContainer.removeAllChildren(), but unfortunately, this is not enough to recover the memory for the images. To truly recover the memory, you need to call:

for each (var child:DisplayObject in myContainer.getChildren()) {
   if(child is Image) {
      (child as Image).source = "";
   }
}
myContainer.removeAllChildren();

My thanks to Russell Brown for this non-trivial solution. I can confirm his results; implementing this solution significantly reduces memory leakage.

Removing Movies: Close the movie
Next, let’s say you want to unload a movie. Most people would just stop the video and remove it from the screen but like the issue with images, this is not enough. Developers should use the following code to properly unload a movie and recover the memory:

for each (var child:DisplayObject in myContainer.getChildren()) {
   if(child is VideoDisplay) {
      (child as VideoDisplay).stop();
      (child as VideoDisplay).close();
      (child as VideoDisplay).source = "";
   }
}
myContainer.removeAllChildren();

Granted, this code assumes you may have multiple movies in your container, although it can be combined with the previous solution to remove images and movies at the same time. Thanks to Ryan Phelan for their groundwork discovering this issue.

Adobe’s Broken Garbage Collector
For whatever reason, simply removing an image or video from the scene and setting references of it to be null is not enough for the garbage collector to recover the memory. If you have an application that cycles through two movies, for example, you may see the memory continue to grow drastically over time as all the previous copies of the video are kept in memory. Hopefully, Adobe will resolve this in future versions of the AIR runtime, but in the meantime developers must take extra steps to sure items have been unloaded and memory reclaimed.

1 thought on “Plugging Video & Image Memory Leaks in Adobe Air

  1. Pingback: Flex – Event Handlers and Weak References | Down Home Country Coding With Scott Selikoff and Jeanne Boyarsky

Leave a Reply

Your email address will not be published. Required fields are marked *