Threads in Actionscript 3

Every once in a while, someone decides they would like to see threading or background processing in Actionscript. While the underlying Flash Player and Operating System use threads, the execution model for Actionscript does not.
For those who don’t know, ‘threading’ is essentially the ability to have the code do something in the background while the UI is doing something else. Because Actionscript is single-threaded, if you spend lots of time doing heavy computation, the UI cannot be updated while you’re doing that computation so your application appears stuck or effects don’t run smoothly.
Similarly, there is no yielding or blocking in Actionscript either. If the next line of code is supposed to run, you cannot prevent the next line of code from running. That means that when you call, the next line of code following that runs right away. In many other runtimes, the Alert window has to be closed before the next line of code continues.
Threading may be a feature of Actionscript some day, but until then, you have to live with the fact that there is no such thing right now.
In other single-threaded environments, you can get something like threads via ‘pseudo-threading’, which involves dividing up the heavy computation into small chunks on your own. (There is no solution to allow for blocking or yielding other than refactoring the application to be even-driven). Pseudo-threading is painful, but doable in most situations. Iterative tasks are easier than recursive ones, the chunk size has to be small enough to not degrade the UI response time and restoration of the execution context must be efficient otherwise you’ll spend too much time saving and restoring your state and not get anything done.
Someone asked me how I would generalize such a thing. I put this together in a couple of hours. It represents my first thoughts, not some deep thinking on the subject. A PseudoThread instance takes a callback function and a context object and calls the callback function with the context object as mahy times as it thinks it can get away with it within the frame interval. The callback function should update the context object before returning and return false when done and the PseudoThread instance dispatches an event and destroys itself.
The following is the a test that loads an image, and adds a red tint to a copy of the image one row at a time. I purposefully slowed it down with trace statements so you can see that it doesn’t do it all at once and doesn’t seem to affect the rotating button.
These two links are the source file and the test image.
the test image
The usual caveats apply (there are probably bugs, limitations, etc). Hope it helps.

83 Responses to Threads in Actionscript 3

  1. mattjpoole says:

    Hi Alex,
    I’d just come to requiring something like this in a project Im working on that uses JPEGEncoder to encode hi res images. This takes along time and I’ve been getting all the UI freezes you mention. My solution was to ‘chunk’ the encoding over frame intervals. So pretty much what you are talking about here.
    I’ll have a looko at PseudoThread later and maybe try to integrate it.

  2. Todd says:

    Hello Alex,
    I’m not sure your demo is woring right for me. I see the rotating button, but the image of the phone to the right is Red from the get go, so I don’t see the one line at a time rendering of the red.
    I’m running inside Firefox with the 9,0,115,0 flash player.
    It doesn’t recolor in a way you can watch on screen. The image is colored in the background. The point is that if I didn’t psuedo-thread, the delay between when you see the original image and the colored image would also cause the spinning button to stop spinning for roughly that duration.

  3. Laurence Taylor says:

    I found a great way of doing this by delegating the task to the player/vm – its also less complicated and conforms to processor speed better. Inside an execute function:
    var delay:Number = Math.round(Math.random()-0.45);
    setTimeout(_execute, Math.round(delay);
    Then call execute again from within _execute if need be.
    By randomising the delay, you force the vm to sometimes create the calls in the next frame, allowing the ui to update smoothly. You can play with the -0.45 to control cpu usage/ computation speed.
    It would be interesting to know if there was a way of working out dynamically what the constant would be, so that it performs consistently on every computer.
    Interesting idea. I would worry that at the wrong frame you’d have several intervals to service and it would interrupt an animation in a noticeable way.

  4. Hi Alex,
    I’ve used your and written a PseudoMutex that enforces ordering of code in different pseudo threads.
    Take a look at this blog entry.
    P.S: Your blog is pretty useful and cool. 🙂

  5. Marcin Glowacki says:

    Hi Alex,
    Do you think we could use this concept to process updateDisplayList for example in DataGrid, and allow smooth movement of the scrollbars? I will try to implement it…
    My DataGrid renders in 0.3 sec when it is full screen. So when dragging the scroll bars, it seems chunky…
    Threads won’t help scrolling. You simply need to get the data on screen and you still have only one processor. Make sure your renderers are optimized. See the examples in other parts of this blog

  6. johnfredcee says:

    As an actionscript newbie trying to code up a mandelbrot set plotter I hit this wall right away. Your blog gave me the hints I needed, although learning that there was no yeilding in a single threaded environment was a bit depressing..:(

  7. swingwind says:

    thanks for the code.

  8. donynam says:

    Multi thread is a must for RIA development. According to the Adobe site, they are going to publish Flash Player 10, however, as I know that they only mention about multi threaded graphic rendering and hardware graphic rendering things (watch the demo from youtube). What I’m thinking is what if the application need to processing thousands line of data in the backend while playing movieclips ? Clearly, Adobe never think properly before they come out with Action Script 3 and VM2.
    Alex responds:
    No, we thought about multithreading AS3, and I think we made the right decision for now. Not everything can be done as quickly as you want it.
    Multihreading is not required to build good RIAs. While it could help some, not everyone needs it.

  9. Miko says:

    What about events? If some component fire event all listening components will receive and process it one by one?
    If you have heavy computation, you can always delegate it to server and let your application to work until results are delivered…this is special case of course 🙂
    Alex responds:
    Event dispatching is synchronous so yes, they will be processed one by one.

  10. Marco Hinic says:

    Hi Alex,
    We have a c++ flash host that implement the Netscape plugin API to play swf files.
    The host is up and running and can be multi threaded with the exception that flash files that have Actionscript must be running in the main thread. Do you have any idea why the flash player should be called from the main thread to have Actionscript running ?
    Alex responds:
    No idea. Sorry.

  11. Aldo Bucchi says:

    Hi Alex,
    I have found that half the time I don’t really need multi-threading, but just a simple, robust AND STANDARD way of queueing method calls ( with recursion and nesting support ).
    Take a look at this small utility class that helps us do just that all around our codebase.
    I am opening a big proprietary codebase and there are some surprises.
    Following up on the PseudoMutex…
    We have a full OS-like framework with scheduling algorithms, priorization,
    etc that we use to schedule hundreds of concurrent queries and parsing processes without blocking the UI.
    I will try to open it some day soon, but there is a lot of work laying around.
    Stay tuned 😉

  12. Sonny Ouyang says:

    Hi Alex,
    We have a legacy report web service that take a while to return an URL (pdf file) of a report request.
    We have built a FlexApp with Cairngorm that sent out requests
    1. to get a list of report category
    2. to get a list of report of a report category
    3. to trigger a report generation.
    4. From a single user point of view, user should be able to trigger multiple runs of report while clicks on UI and get back list of report category and report list.
    Could you please point us to a possible direction?
    Alex responds:
    That’s not quite on topic and out of my area. Post on FlexCoders or hire Adobe Consulting

  13. Hi Alex!
    I just finished a flow based programming framework for AS3 and it’s based around your code. What license are you using? I was personally hoping to let it be under the MIT license. Is that okay with you?
    Thanks in advance!
    Alex responds:
    Yeah, you can publish it any way you want. If you make millions somehow, share it with me.

  14. I’m brushing up on Flash coming from Java.
    According to the docs, communication between several flash apps running on a single machine is possible and well managed.
    I would expect that concurrency can be achieved by breaking down the workload between several applications(?).
    Alex responds:
    Yes, but communication between SWFs is asynchronous and not guaranteed to preserve types and slow, plus you can’t really startup SWFs on the fly (you can, but will launch another browser). Still, it might be a solution for some folks.

  15. Roxsarah says:

    Hi Alex,
    I am Master’s student and my thesis is creating a new plug-in for one of the google open source project, which consists of several modules like chat, conference,.. that each client needs to send notifier of his current status to all other clients like what he is doing in all moments. I read your blog and I guess using thread can be useful for this regard. I’d appreciate if you help me. Plug-in is in the flex and I have to use Actionscript. This plug-in has minimum functionality which are working dynamically along these modules, like updating the status, history,..
    Many Thanks in advance,
    Alex responds:
    I would ask on FlexCoders. I probably can’t help you directly.

  16. Lazar Kirven says:

    Hi Alex,
    I like the PseudoThread class. It is a minor improvement, but I hope Adobe is seriously considering the Thread implementation in new players because it is not enough.
    Alex responds:
    It gets talked about, but nobody wants to do it yet. It would increase the player’s footprint, and we’d have to figure out how to get threading and our frame/script/render model to coexist.

  17. donynam says:

    Hi Alex,
    So far, I have created a threadClass(pseudo-threading) which support suspend, awake, stop.
    After testing I found that it is very hard to apply multithread in component. Because it is too hard to split component(such as datagrid) to a few pieces and execute it. To make the effect of the component goes smoothly, there is not other way, but suspend all the background running task.
    threadClass might work in small and simple module but not in a complicated application.
    Alex responds:
    Yup, Pseudo-threading is not true threading

  18. Raz Gilad says:

    Hi Alex
    As a new comer to flex from backend applications (java, C++, etc) I must admit I’m a bit confused.
    I understand that there is no code blocking in flex – so if I open a window (e.g. popup) the next command will be executed even if the window may still be opening and code associated to the “creation completed” it is still running. My question is why this is not considered to be multithreading? As both the calling code and the window “creation completed” code are running in parallel.
    My second confusion is with the relation between code and the UI.
    I’ll try to explain with a simple scenario:
    Code running on 1st window activates a procedure on the 2nd window.
    The procedure updates some visual aspects on the 2nd window (e.g. color).
    While the procedure runs, the calling code is waiting on the 1st window (which makes sense). Now assume that the procedure does not return (e.g. endless loop or similar). The visual aspects of the 2nd form will never be updated. Does this means that UI is only updated if no code is running?
    Alex responds:
    1) It is not multithreaded. The next line will not run until after the popup returns from being created. The popup creation may return before creation complete because of invalidation, but if your code that follows the popup keeps running, you’ll never see the popup.
    2) Flash uses a deferred rendering model. Scripts run and update the display list objects, but the screen is not updated until scripts stop running, then the screen is rendered based on the current state of the display list objects. If your scripts do not stop running, Flash will kill the scripts after 60 seconds.

  19. Hey Alex! Thanks!
    I posted my “framework” to Google Code. It needs a lot of work but it’s an interesting concept to look at.
    Here’s the location of the framework:

  20. jitendra jain says:

    Alex! you are simply great!!
    you made my life so easy. your item renderes memory leaks blog and this blog help me a lot. God bless.

  21. donynam says:
    I just found some useful resources that talk about implementation on thread library by manipulating the event.
    However, I think that the direction of making real multi-threading library in VM is building up the time sharing system, but not building it through the event handle trick.
    Recent days before, I found that there is one fascinating feature in Flash player 10 called pixel bender. According to Adobe, pixel bender runs in different thread. Maybe we can use pixel bender to overcome the graphic update delay issue during code execution period ?
    Alex responds:
    Well, PixelBender is its own thing and isn’t part of ActionScript so while you might be able to do some things with it, it won’t allow you to multithread code written in ActionScript.

  22. Is there any way to use the PseudoThread class in an FLA file authored in the Flash development environment rather than Flex? I assume I could use fl.core.UIComponent in place of mx.core.UIComponent, but there doesn’t seem to be a Flash equivalent to mx.managers.ISystemManager.
    Alex responds:
    Should be possible. Try to hook up to “enterFrame” event

  23. nathan rogan says:

    I would think that the threading issue will be the deciding factor in many developers choosing either Silverlight or Flex. I personally love Flex but am having major issues as I develop larger application. 🙁

  24. Rob Cole says:

    I just saw a demo of Silverlights thread support – its well done. Ive been a die-hard Flash/Flex programmer for years, but Adobe had better be very worried about Silverlight! – Its been designed from the ground up for internet apps (albeit by borrowing much of the innovation, as Microsoft is wont to do…), as opposed to Flash which started its life as an animation tool.
    Alex responds:
    As we hear more from our users about the importance of threading, the higher its priority will be.

  25. Josh Strike says:

    I have to disagree with the reader who said multithreading is a requirement for RIAs. It’s actually almost impossible to imagine a scenario in which you’d want to do that much data processing on the client’s machine. If you want to write really heavy number-crunching code, Flash just isn’t the way to go. It works superbly as a single-thread environment that can act as a front-end to all kinds of multithreaded server processes and tie them all together, keeping everything smoothly animated by listening for callbacks and events… if you wanted to process massive amounts of data locally, wouldn’t you want to write the code in c++ or java anyway?
    I think Adobe made the right decision in this case…

  26. Je Ne says:

    What about a approach of adding non-visual threads? Idea is keep current VM main thread for complete Flash app, add ability to spawn threads that can NOT execute visually. So, can say run a expensive process in separate thread and not worry about current frame/event model????
    Alex responds:
    It’s been considered. The language would have to change to officially support it. You can unofficially do something like this by writing your non-visual threads to run in PixelBender. Haven’t tried it myself yet, but it should be doable.

  27. Jereme says:

    Hi Alex,
    I have to agree with others that not having multithreading in AS3 is a really big problem. For small simple applications it is not a big deal but to create any kind of complex application, especially a desktop application using AIR, multithreading is definitely needed.
    I am currently developing a desktop application using AIR and I am a bit disappointed in the overall performance. At this point I am getting close to scraping the AIR platform and moving to .NET.
    I am not trying to bash AS3 and AIR. I have been a AS programmer for 8 years now. I was just hoping for better performance and flexibility from AS3 and AIR.
    Alex responds:
    Actionscript is in a tug-of-war between being a scripting language and a language more like Java. The runtime must remain small, and the player’s execution model doesn’t really allow any code to run forever right now. Everything must stop every once in a while to allow the player to render.
    Threads may show up in some future version of the language but I wouldn’t hold my breath waiting.
    However, 9 out of 10 times, when someone says they need threads, they don’t. Threads are really only useful if the CPU has spare cycles. If the CPU is already completely busy cranking, threads just slow down when it will get done. Optimizing the code often is the better solution, and if you do need threads, it is now possible via PixelBender

  28. Jereme says:

    Thanks for the reply Alex.
    Do you have any tips on how to improve the performance of the ADG (AdvancedDataGrid)? That is one area I keep running into problems with.
    For example I am using HierarchicalData with an ADG and displaying it in a tree structure. When I have several hundred items in the ADG the preformance really suffers. A lot of times my app will freeze when rendering changes to the ADG.
    Any tips on how to prevent this freezing?
    Alex responds:
    I would run the profiler and see where the time is going. Make sure your renderers are optimized. That usually makes the biggest difference. Don’t use containers or databinding in your renderers.

  29. donynam says:

    I don’t think “Actionscript is in a tug-of-war between being a scripting language and a language more like Java”.
    What I’m thinking is Actionscript need to find some other way to solve the multi-threading limitation. for example ,Adobe is going to use PixelBender to implement multi-threading.
    Some of them argue that most of time we don’t need multi-threading to complete an application. It is true. However, most of the time we are not talking about whether this application can be done in multi-threading way or non-multi-threading way. Actually, what we focus on is application performance. Optimizing of code could help better performance, but we all know that the truth is most of the multi-threading application is faster than non-multi-threading application.
    Since Adobe come out with PixelBender which execute differently from main thread. I think it is time for Adobe to think about how to manage this kind of thread.

  30. judah says:

    I’ve looked at a post on multithreading with pixel bender but it seems to be limited to math operations. Is this correct? What about creating a second swf, connect to it through local connection and use it as another thread? I suppose the downside is that you can only pass strings or json objects through it if it works.
    Alex responds:
    Second SWF and LocalConnection is possible, but depending on how much data you need to communicate between the two SWFs, the connection might become the bottleneck.
    In theory you can do just about anything with PixelBender that involves cranking through data. I don’t think I’d use it for input or output or interactivity, and most of the things you want threads for are data-intensive. If you think you want to thread some UI work, you might want to examine your design and have the threads crunch your data model and have a single UI thread do the updates

  31. Scott Roberts says:

    Well said donynam, it’s about performance.
    Alex, it’s all about the user experience, right?
    A non responsive UI really sucks for users … say . when they are trying to manipulate a large image.
    My code could not be more optimized, so what’s a developer to do?
    Yep, cut back the feature, make it less engaging to get the job done.
    In short, sacrifice User experience to ensure the responsiveness of the app.
    Not good for the User, not good for the developer and not good for Adobe.
    Found your blog from:
    “Alex responds:
    As we hear more from our users about the importance of threading, the higher its priority will be.”
    Please count this as a vote from me to help me stay away from Silverlight … I like Adobe much better, but I like my Users best so I’ll go with whatever platform gives them the best … experience.
    Alex responds:
    If you’ve really got that much data, then you’ll at least need to show a wait cursor while you crank it. It is usually straightforward to crank image data in pseudo-threads, and doing it in multiple real threads wouldn’t actually save the user time, it would just let them do something else while waiting longer for the results.
    FWIW, if you are doing image manipulation on a per-pixel basis in actionscript, you are not fully optimized. You might want to consider using PixelBender, ByteArray, Alchemy (someday) and existing Flash filters and transforms to have the player do what you might be trying to re-write in your code. The player has lots of image manipulation APIs built in.

  32. yuku says:

    > As we hear more from our users about the importance of threading, the higher its priority will be.
    I tried to create desktop application that loads data from a 2MB text file and parse it. I need to do manually the splitting of processing time each frame. It will take a long time if the time slice is not big enough. It became sluggish as the time slice is too big. event.updateAfterEvent does not affect anything when the only thread is processing that text file. So even the UI become less responsive.
    Alex responds:
    You only have so many CPU cycles to use. If your UI takes a lot of them, you may need to optimize there. If the background process is taking too much, you need to throttle back on that.

  33. Scott Roberts says:

    Thank you for taking the time to respond Alex.
    Yep, up to 10, 20, etc. MB per file. You got it though, we need our Users to be able to complete other tasks while any processing happens in the background so we’re doing this across frames.
    Yea, we’ve tried SetPixels, PixelBender, ByteArray, Flash filters and transforms to have the player do what we want. But we’ve found Alchemy to be the best hope for us. Without Alchemy, we’d be on Silverlight.
    Take it as a compliment, your dev base is doing things with Flash no one would have dared to try even a year ago.
    We were laughed at during a recent developer meeting when I said we were using Flex to do what we are doing … until they saw the results.
    We’re getting all that we can out of the Flash Platform and we want we want more. 🙂
    So, where are things going next?
    Thank you
    Alex Responds:
    I wouldn’t hold my breath for real threading. Processing that much data in a virtual machine is problematic, but there’s a lot of people worrying about actionscript performance right now so we’re hoping to see faster results over the next several releases

  34. Jason says:

    Hi Alex, has it ever been considering to add a DoEvents() function similar to VB? I realize it might result in some sloppy practices, but a function to basically tell Flash to run another frame and then return might really ease up the pressure to have full thread support?
    Alex responds:
    Things like that have been considered, but the Flash runtime model is different from Windows and has to work on all platforms so such a thing doesn’t really make sense.

  35. Stanley Guan says:

    “While the underlying Flash Player and Operating System use threads, the execution model for Actionscript does not.”
    Here are some of my questions:
    1) Does AIR runtime use threads?
    2) Do you know what SWF files could be possibly run in separate threads within Flash Player? For example, modules loaded to main application, subapplications loaded to main application, multiple AIR applications run on a client.
    Will appreciate your answers.
    Alex responds:
    1) AIR actionscript execution is also single-threaded.
    2) All SWFs loaded by a Flash Player are all executed in the same thread.
    The threads in Flash and AIR are not used to process code in application SWFs. Any threads do operating system stuff like get the list of installed fonts.
    There is no way to get your actionscript code to run in threads.

  36. Naik says:

    Hi Alex,
    i would like to know whether we can run a service kind of thing in action script 3.0 which runs in back ground and keeps checking for some URL is available or not .. or say network connectivity is available or not.
    Alex responds:
    You can set up a timer to check periodically.

  37. firemonk says:

    I am developing an application to record audio and at the same time user is drawing on the whiteboard. I have noticed that the recording stops while the the user is drawing on the whiteboard.
    Is it possible for me to use this.
    Alex responds:
    If there aren’t enough CPU cycles then, no, it won’t work. However, there should be on most computers. You might have to optimize the whiteboard code so it uses less CPU. Run some tests: does recording stop when just moving the mouse? Run the profiler: How much work is being done by the whiteboard code?

  38. Leha says:

    Hi Alex,
    I have performance problems in TileList displaying a bunch of local images. I use Loader class to decode image and place it into ItemRenderer. But UI freezes during each Loader.loadBytes() call, so TileList cannot be scrolled smoothly.
    Is there any way to avoid this? I suspect that I’m doing something wrong, because it seems that Photoshop.Online doesn’t have such problems. All lists in its UI works smoothly and it looks like it loads images asynchronously?..
    But I have no idea how to prevent UI freeze. In my case I cannot break task of loading of single image into a smaller chunk. Could you point me in some direction?
    Alex responds:
    Look at using SuperImage by

  39. Ben says:

    Why threads?
    Sure Alex, image and sound data manipulation is so fast in AVM2.
    AVM2 is capable of things you can’t do on bare metal without threads – so why make the silly excuses?
    If people don’t write multi-threaded code, they’ll never have cross thread problems. Those that do write it, will know how to do it properly.
    If Adobe added threads in FP11, the community would rewrite thread-safe Flex components in a matter of days – because they want them.
    Look at it this way:
    Many people want threads.
    No people want to not have threads.
    Alex responds:
    OK, we’ll wait and see…
    Will thread-safe components be smaller? faster? easier to debug? help you get your app developed sooner? I have my doubts…

  40. Italo says:

    Nice Article. I need to print a long report in Flex. The case is that the application does not finish sending the pages to the printer because the error ” A script has executed for longer than the default timeout period”. I try to apply your solution and some how it does not work for printing processes. The “thread” function which suppose to add the objects to the FlexPrintJob is only triggered after the FlexPrintJob object is closed because no page is being added. Any idea how to address this situation. I would really appreciate your comments.
    Alex responds:
    Printing is done by the player and unfortunately the player team has not been able to get to fixing the bug that prevents printing from working in the “background”. Their bug base is public now so go file a bug and get others to vote for it.

  41. takiz says:

    i’m also facing the same problem with you, i think should find another way, if that’s problem occurred in flash player

  42. Paul says:

    I have a need to multithread and I think will be useful for that. However, I wanted to put this out there to see if anyone has better approach to suggest – My app need to play multiple videos in succession and I want to start buffering the next video before the current one ends so that there is no gap between two videos. Is there a good way to do that?

  43. Max says:

    Another brother calling for threads. I build on Air and threads would help my life, If for many reasons threads scare the player dev team, may I suggest a simplistic approach, I may be saying nonesense but maybe simply offer a single other thread next to the main player thread that is available should a developer need it. I don’t know, I’m not going to implement 3dsmax in flash but it would help for example processing needed data coming in from the server instead of me having to sprinkle the data flow throughout the app so that it doesnt clog up the UX.
    Threads please. Thanks
    Alex responds:
    You miight want to leverage PixelBender for now.

  44. Multithreading??!!! YES!! we need it!!!!
    I only can use 100 markers in my Flex application because it freezes the UI.
    very very annoying with this problem…AS3 is like a toy compared with Silverlight.

  45. Bradley says:

    Yet another brother calling for threads.
    I would agree that 90% of the time people saying they need threads don’t actually need them. However, one side effect of multi-threading is that it tends to clean up the code and make it more readable. Simpler code is easier to follow and debug.
    Right now if I want to make a remote call I have to create and setup a bunch of different listener functions to handle the various types of exceptions and responses. If Flex allowed multi-threading, I could do everything in a single, simple, easy to understand function. Something like this:
    try {
      var ro:RemoteObject = new RemoteObject(…);
      var response:Object = ro.getSomeData(…);
      someControl.dataProvider = response;
    } catch (SomeException1 ex) {
      // handle exception
    } catch (SomeException2 ex) {
      // handle exception
    } catch (SomeException3 ex){
      // handle exception
    IMHO, this code is easier to understand than the existing syntax where the code handling the response to the remote call is scattered about in different places.
    Alex responds:
    I doubt that the main thread will ever be fully synchronous. Flash is pretty dependent on the deferred- rendering frame-based execution model. Maybe if we do worker threads someday you can put asynch i/o in such a thread.

  46. Steven says:

    I need threads for a papervision3D RIA. I want to show low detailed objects during loading high detailed objects. But the application is unusable while a loadingprocess is active.
    I think threads are very important for the future of flash.
    Alex responds:
    Please provide more detail. Loading is normally asynchronous and won’t block user interaction.

  47. David says:

    Hi Alex,
    one and a half year after you published your article it is still very interesting. In our company we use Flex in combination with the Cairngorm framework to do our server – client communication. Threading or at least a worker thread would be very useful in our environment since we automatically update the data of hundreds of flex clients every minute. We hope that this topic advances with the Flex framework.

  48. Bob F says:

    “Threads are really only useful if the CPU has spare cycles. If the CPU is already completely busy cranking, threads just slow down when it will get done.”
    That assumes there’s only one CPU available. All newer computers have at least two CPUs, and AS3 coders only have access to one of them (PixelBender aside). That’s a big issue for anyone writing a CPU intensive RIA.
    “I wouldn’t hold my breath for real threading.”
    Oh well, thanks for letting us know you stand.

  49. Dennis says:

    What a pity… flash runtime is too strong graphic engine that cannot handle threads. In today’s world, computer are fast because they do all the jobs simultaneously, in precise are pseudo-fast, but fast for humans. So Adobe, do your magic you owed to do! In multi core world, threads are demanded.

  50. Jim says:

    One more vote for threads. Please.

  51. HzD_Byte says:

    Threads are really useful feature – they are irreplaceable with Alchemy project (i.e. callback functions).

  52. S.B. says:

    +1 for multi thread.
    I’m a young computer scientist and without it I will not choose flex for my project even if all the other things are very interesting.
    I don’t need it now, but you should know that we have to be sure that we can do everything in the future (for specific applications but for our standard program too!)

  53. James Ward says:

    If you want to see real threading support in Flash Player then please vote for this feature request:

  54. David says:

    I am from China. My programmer tell me this is the best optimization while I see the UI lagging on the screen. and they say multi-thread can easily solve the problem but now , this level of lagging is the best optimization. after reading this post, I can’t hold my breath to ask my programmer to try silverlight. no offence.

  55. Philippe says:

    Please thread please. Otherwise silverligth

  56. Alex Harui says:

    I would recommend that you sit down with your programmer and go over a performance profile of your application and see if you can identify ways to further optimize your application.

  57. tajuddin says:

    Is it possible to create thread in flash. The situation is i want to call PHP file (for example upload.php) from web server. That web server have 4 DNS, for example,, and I want to call this upload.php in parallel using url,,, and
    It is possible?

  58. Alex Harui says:

    Flash does not support threads at this time. Your requests will be handled asynchronously and dispatch individual events when the data transfer is complete.

  59. Christophe says:

    I have a long processing function in my application. I just want to display a busy cursor before the processing starts. I tried this:
    But the cursor only changes after the processing.
    Can someone explain why this isn’t working ?

  60. tajuddin says:

    Dear Alex,
    What if, i want to download single image 320MB size from web server. I use flash to download that file. However there is a TCP window size issues. Therefore the download process took a long latency/time. Then i think that instead of one single image 320MB, I divides into 8 files of 40MB size. I want to download 8 images 40MB size parallel. Perhaps it will reduce the download time. Is it? thank you for your help.

  61. Guru says:

    I have a app where smaller images need to be created from bigger images. The bigger images count will be close to 1000+ and smaller images count will be close to 100K. Which one of the following option is ideal for this
    1) Load bigger images one by one, complete the cropping of smaller images from the bigger image- synchronous operation
    2) Load bigger images asynchronously for creation of smaller images

  62. +1 on threads.
    I’m seeing some serious misconceptions about threading in the comments here. Having multiple threads WILL make your application faster, you don’t need two CPUs or two cores. Yes, you have to know how to use them.
    All UI toolkits have a single-threaded programming model, but All UI toolkits have multithreading available except Flex (though Flash uses multithreading itself).
    Asking developers to spend weeks to optimize what is happening on the UI instead of offering a way to offload that work to another thread (as is done in all other UIs) shows that Flex’s architecture is seriously flawed. It works, especially for many Flex apps since they are simple. There are ways around it, like having the server do all the serious work.

  63. tajuddin says:

    Dear Alex
    How to open two http connections in flash.
    thank you

  64. Alex Harui says:

    callLater can trigger on RENDER which is effectively the same frame. Maybe try two callLaters or listen for ENTER_FRAME

  65. Alex Harui says:

    I don’t know if that will help. There can be lots of bottlenecks getting that much data from a server, and no guarantee that it will all show up “in parallel”.

  66. Alex Harui says:

    I’d load big images one by one and cut them up via a pseudo-thread and then try to get rid of the big image from memory before getting the next one.

  67. Alex Harui says:

    Two HTTPServices or two URLLoaders

  68. dave says:

    I have a small reporting app that connects to an old webservice for data. The data return is not optimized ( flat ) and there is no ability to paginate the data set – thus it returns huge sets – sometimes 18-20K rows. when i reach this amount the flash player freezes (even the simple setBusyCursor() ) while it parses the return. Is this a situation where your PsuedoThread class could be applied? And if so – how would i go about using it on the setBusyCursor?

  69. Alex Harui says:

    It depends on what is happening with the data when returned. If you are using WebService you probably get back SOAP/XML. If you turn it over to the SoapDecoder it will take a long time. You could write your own decoder that uses pseudo-threads to decode a few objects at a time.

  70. Joe says:

    “You can unofficially do something like this by writing your non-visual threads to run in PixelBender. Haven’t tried it myself yet, but it should be doable.”
    Not really. PixelBender can do bigtime nuber crunching, but it needs to be invoked on every frame by the Flash player. So if you’re looking to start a thread to do an expensive process, then pick it up when that process is complete, you can’t do that with pixelBender. This means it can’t be a background process, which is what I think most people are missing.

  71. Jeff says:

    @Joe, I’m pretty sure that’s false. Just Google for pixelbender threads. We use them in our product; they’re just not easy to setup, nor do they run actionscript code.
    So now that JavaScript has introduced Web Workers (, seems like pressure for Flash to do something. The nice thing is that Flash will likely be able to use JavaScript Web Workers through the External Interface, but that means we still have to program in javascript.
    Also on the topic of multi-threading, why can’t multiple SWFs on a given web page be threaded separately? Wouldn’t it be beneficial in case one SWF (i.e. an ad) does something stupid or is too intensive that it blocks the other content.
    I also did a quick experiment and noticed that heavy JavaScript calculation blocks flash content, too. Maybe it’s a restriction of the browser that JS and AS3 share resources?

  72. Sam H says:

    @Alex – Alex, can you please attach an explicit license on your code snippets? my company requires that code that we use be released under a copy left license like LPGL or MIT/BSD. Gracious as you are with your contributions, I think it will be very beneficial for those of us who are required to conform to these restrictions.

    • Alex Harui says:

      I’ll look into it. I doubt I’ll have time to update all the source that is currently posted, but I’ll try to add a license to new code.

  73. Zet says:

    Oh my. I stumbled on this:

    It’s pretty much a slightly copy paste version of your code. And the modification is copy paste programming as well, so he even copied twice from you ;). Probably you don’t care about this, but still…

    Besides that matter – it would be nice if AS3 supported coroutines or continuations … that would ease approaches like this and would avoid the troubles of native threads, but you probably also know this as well 😉

    • Alex Harui says:

      Imitation is a form of flattery. Everybody has their favorite concurrency model. I’m not sure when we’ll decide which one to go with.

  74. Gerry says:

    AS3 definitely needs some form of concurrency. And not just refactoring our code to use pseudo-thread approach. This only works for very simple applications.

    WebKit supports Web Workers. Maybe this should be implemented in AS3?

    And haXe uses NekoVM and is capable of multithreading. Maybe enhancing AS3 to use NekoVM is another way that threading can be achieved.

  75. Celsyum says:

    +1 for multi thread.
    I dont like silverlight , but new version will support 3d and multithreading… no… I will still keep believing in Flash and Adobe’s work. Thanks for AGAL.

  76. Curtis says:

    I have a couple questions:

    thread.systemManager.stage.invalidate();;, 0);, 0);

    The first line seems to be causing a render even to dispatch on thread, but the other 3 lines don’t appear to be doing anything. Are those lines for backwards compatibility?

    2) Why do you only subtract the RENDER_DEDUCTION when the mouse moves or there is a key press?

    • Alex Harui says:

      If you don’t need the last 3 lines, that’s probably ok. I might have needed that in older players.

      Mouse and Keyboard events are handled in-between frame events.

  77. Dinko Ivanov says:

    Thanks a lot!!!!
    A life saver! 🙂


  78. Ian Knowles says:

    +1 for multithreading…

    I’m not going to bitch about it. All the arguements for it have already been said a thousand times over and now with AGAL Im sure there will be allot more devs wanting to use all of the power available from the hardware. Most devs fully realise things take time and I think AGAL was far more worthy than multithreading. However I would like to add myself to the list of devs that wants it.

  79. Zapata says:

    really long post. guess it shows the need of multithreading
    i expand at the moment a GameEngine with a Prefetching/Caching-System. The Problem at the moment is the lagging of the UI when doing some background calculations, needable to generate priorities for the assets from a level (2D-Point-and-Click-Game). everytime the character is send to some position the UI laggs about 2 seconds before the char starts moving. frustrating for the user. I develop with pure AS3 and FlashDevelop, can Pseydothread solve this Problem?