Unloading modules in ubuntu

Hi,
How can I unload modules in ubunt (e.g., graphics module, keyboard, USB etc)?

umairalipathan, please post questions about Ubuntu on their forums: http://ubuntuforums.org
Also see: https://wiki.archlinux.org/index.php/Fo … ow_to_Post
Closing.

Similar Messages

  • [solved] Unloading modules before suspend to disk

    Hi, I'm trying to get my Asus U36jc to suspend to disk and resume. Suspending seems to go fine, but after resuming I get an unresponsive notebook (no response on key presses or ping) showing a black screen. Then immediately the fan gets louder and the notebook gets warmer.
    Just before the machine goes to sleep, I see this in my screen:
    xhci_hcd 0000:04:00.0: PCI post-resume error -110!
    xhci_hcd 0000:04:00.0: HC died; cleaning up
    xhci_hcd 0000:04:00.0: HC died; cleaning up
    dpm_run_callback(): pci_pm_resume+0x0/0xb0 returns -110
    PM: Device 0000:04:00.0 failed to resume async: error -110
    hda-codec: out of range cmd 0:20:400:fffff7ff
    I found this guide (https://www.kernel.org/doc/Documentatio … ugging.txt) and using that I determined that when I first remove modules ehci_pci, ehci_hcd and xhci_hcd, suspend to disk and resume seem to work fine.
    I found out here (https://wiki.archlinux.org/index.php/Pm … end_to_RAM) how to unload modules prior to suspending to RAM, but that doesn't seem to work for suspend to disk, and I can't find how to unload modules prior to that. Can someone tell me how to do that?
    Thanks for any help!
    Last edited by diederick76 (2013-09-25 20:27:36)

    I'm not sure if pm-utils is deprecated, it doesn't say so here (https://wiki.archlinux.org/index.php/Pm-utils). In any case its a dependency of upower, which is a dependency of kdelibs, so as long as I want to use KDE my harddrive is stuck with it.
    However, I decided to try your suggestion to use systemd:
    # asus36JC.service
    [Unit]
    Description=Script upon suspend/resume
    Before=sleep.target
    StopWhenUnneeded=no
    [Service]
    Type=oneshot
    RemainAfterExit=yes
    ExecStart=/home/diederick/bin/no_modules
    ExecStop=/home/diederick/bin/modules
    [Install]
    WantedBy=sleep.target
    It seemed to work perfectly for a couple of times in a row (modules were there before and afterwards) until I restarted the notebook, when the problem was back. But then I remembered to enable the service and now it works. Thanks a lot!

  • Unloading Modules in Flex

    What does the debug trace [Unload SWF] mean?
    As per this blog
    http://blogs.adobe.com/tomsugden/2010/02/how_to_unload_modules_effectively.html
    "This trace indicates that the module have been successfully unloaded"
    Is this true?
    I am unloading a module, I see the [Unload SWF] trace, but after unloading, if I try to create an object of a class contained in the unloaded module (using reflection), I am still able to create it.
    Am I understanding it wrong?
    Thanks!

    That means that the bytes of the SWF have been removed from memory.  I'm not
    sure if you're just getting lucky or if there is some other thing going on.
    Post a simple test case.

  • [solved] unload module alx on suspend fails

    Hi!
    I'm having trouble getting my ethernet card to work properly with  suspend to ram (pm-suspend). Its a Qualcomm Atheros AR8161 Gigabit Ethernet Adapter (builtin ethernet-card of the Asus N56VZ) that I'm running with the alx-module that I build from the compat-drivers (compat-drivers-3.9-rc2-2-su, so version 1.2.3 of the alx module) on kernel 3.8.8-2. The driver works fine except it breaks suspend. A first suspend works fine (see suspend.log, upper part), however, after resuming, NetworkManager does not detect a cable being plugged in. Trying to suspend again fails results in the lower part  of suspend.log. Removing and probing the module again (reload.log) seems to work fine and resets the whole thing (network works, one suspend works, all following do not work)
    Logs see https://gist.github.com/anonymous/5467609
    I created a file SUSPEND_MODULES="alx" /etc/pm/config.d/modules (rights 644) that as far as I understand is supposed to unload and load the module upon suspend and resume but for some reason this does not seem to work properly. Why is that, am I just missing a typo? How can I fix it?
    Any help is appreciated!
      Hannes
    PS:
    $ lspci -v
    04:00.0 Ethernet controller: Qualcomm Atheros AR8161 Gigabit Ethernet (rev 10)
    Subsystem: ASUSTeK Computer Inc. N56VZ
    Flags: bus master, fast devsel, latency 0, IRQ 19
    Memory at f7800000 (64-bit, non-prefetchable) [size=256K]
    I/O ports at d000 [size=128]
    Capabilities: [40] Power Management version 3
    Capabilities: [58] Express Endpoint, MSI 00
    Capabilities: [c0] MSI: Enable- Count=1/16 Maskable+ 64bit+
    Capabilities: [d8] MSI-X: Enable+ Count=16 Masked-
    Capabilities: [100] Advanced Error Reporting
    Capabilities: [180] Device Serial Number [...]
    Kernel driver in use: alx
    PPS: This bug is related and it has been reported that SUSPEND_MODULES is a workaround: https://bugs.launchpad.net/ubuntu/+sour … ug/1130037. There has just been a bug filled that is kind of related: https://bugs.archlinux.org/task/34971 but I'm not sure if its of any use if I postmy information there.
    PPPS: This is also kind of related but does not provide any information http://askubuntu.com/questions/263867/u … -lid-close (I just list it for documentation purpose)
    Last edited by HaMF (2013-05-07 14:02:50)

    „Sleep hooks
    Systemd does not use pm-utils to put the machine to sleep when using systemctl suspend, systemctl hibernate or systemctl hybrid-sleep; pm-utils hooks, including any custom hooks, will not be run. However, systemd provides two similar mechanisms to run custom scripts on these events.” – from wiki, so the sad thing is it's not as easy as in Ubuntu.
    But (I guess) it's not impossible. I've got the same problem with ALX so I'm gonna try to make my own hook based on Wiki tips. Currently this Wiki page https://wiki.archlinux.org/index.php/Pm-utilspm is outdated (for Systemd user), so I'll try this section https://wiki.archlinux.org/index.php/Sy … management .

  • Problems unloading Module

    So we have a project that has two states a 'Welcome' state and a 'Module' state.
    We have two types of modules. One module is of type TestLab which is a component we've created. The other type of module is a blank view that will show popups as they're called.
    The problem we're having is very strange and hard to pin-point.
    If we load TestLab A, then unload TestLab A, load TestLab B, unload TestLab B, load TestLab A......all the modules are cleaned up properly.
    But if we go from TestLab A, to welcome screen, back to TestLab A....TestLab A will not have unloaded the first time and we'll have double modules, although we're calling the exact same code to unload and load the module.
    It's also the same thing if we go from TestLab A -> other module - > TestLab A.
    Although if we go to TestLab A -> welcome -> TestLabB -> TestLab A, everything is cleaned up properly.
    So it appears in order for a module to be properly unloaded and released from memory, we must load a different module of about the same size.
    Anyone have any idea what may be the culprit. It's just very strange to me that modules can be unloaded and released sometimes, while other times they hang in memory depending on what module was loaded after it.

    Unfortunately, that isn't my area.  I would ask on the FlashBuilder forum.
    Did you verify that the preloadSWF entry in mm.cfg looks the same when it
    works profiling a simple app?
    Also, when you're not attempting to profile, there shouldn't be a preloadSWF
    entry in there.  Sometimes FB fails to remove that entry so deleting it
    might help.  FB will re-add the preloadSWF entry as needed.
    Another thing to look into is FlashPlayer Trust files.  They should be set
    up automatically by FB, but occasionally an custom configuration fools the
    setup.  They are stored in different places based on your OS.  Search the
    Adobe site for details on where they go.  They are typically used to get rid
    of security errors when running apps from file://

  • Systemd service for virtualbox loading/unloading modules too

    I'd like to have a vbox.service that handles inserting/removing the needed modules as well as running the target vbox.   I modified ngoonee's service as shown below to handle the modprobe and rmmod steps but I have two issues:
    [Unit]
    Description=Virtualbox Headless VM
    [Service]
    ExecStartPre=/usr/bin/sudo /usr/bin/modprobe -a vboxdrv vboxnetflt
    ExecStart=/usr/bin/VBoxHeadless --startvm narch
    ExecStop=/usr/bin/VBoxManage controlvm narch poweroff
    ExecStopPost=/usr/bin/sudo /usr/bin/rmmod vboxdrv vboxnetflt
    User=facade
    [Install]
    WantedBy=muti-user.target
    Issue #1) The service fails when trying to run the ExecStopPost command since the vbox doesn't go instantly down and the modules are in use.  So, without building in a sleep command... how can I have the rmmod run when the poweroff of the vbox takes some time?
    Issue #2) To my knowledge, I cannot mix root user commands and user-defined commands, my solution has been to use sudo but I think that isn't very elegant.  Is there a way to have the User= statement only apply to the ExecStart and ExecStop commands?
    Last edited by graysky (2013-11-24 10:16:54)

    Try a separate service for loading the modules (with unloading on stop and StopWhenUnneeded=true so the unloading happens as soon as you no longer need them). Add Requires and After to the VM service (now you can also have multiple VM services without modprobe/rmmod conflicts). This should clear up #2 as well.
    If you're lucky, this fixes #1 too.
    (I had written some more, but then I wanted to check something with VBox and it crashed my system -- it's done that a few times recently.)

  • Load unload module

    hello
    i have a main mxml file with x mxml module file
    and i search how i can load and unload the module file by my
    main mxml file
    thank for your help

    You might need to use a shared code module to load the remote classes so
    they don't unload.
    Alex Harui
    Flex SDK Team
    Adobe System, Inc.
    http://blogs.adobe.com/aharui

  • Load/unload modules automatically

    Hello guys,
    to be able to eject a disk after pressing the eject-button of my cd/dvd drive I have to unload/load the modules manually with the following commands:
    rmmod sr_mod
    rmmod cdrom
    modprobe cdrom lockdoor=0
    modprobe sr_mod
    After that I can eject it without any problems. I thought I can automatise this by adding options cdrom lockdoor=0 to /etc/modprobe.d/modprobe.conf and finally load the modules in my /etc/rc.conf like the following:
    MODULES=([...] "cdrom lockdoor=0" sr_mod)
    But it still doesn't work. What's wrong?
    Thank you in advance.

    brebs wrote:
    orschiro wrote:why is this done
    Linux isn't designed to be user/newbie friendly. That's the reason, in a nutshell
    I see you are going through a phase of discovery. I too fall prey to such revelations of clarity, which often manifest themselves in the most forthright and cynical reality imaginable.
    I think I might like being a dreamer better.

  • Unloading Module Closing Multiple Custom Panels

    I have a requirement where in  same screen can be openned N times, i have written a custom panel (module loader inside it) with a close buttonn, to load the same module multiple times. The problem is when i close one panel all the panels are closed. The reason it is closing all the panels is i have included the removeChild inside unload tag of the module loader.
    I tried changing the "ml.unloadModule();" to "parent.removeChild(this);" then i acheive what is needed close only the panel that is closed, but the module it not unloaded. Is there any way i can acheive closing only a single panel (this is closed) and unload the module. 
    Below is the custom panel code:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Panel xmlns:fx="http://ns.adobe.com/mxml/2009"
                         xmlns:s="library://ns.adobe.com/flex/spark"
                         xmlns:mx="library://ns.adobe.com/flex/mx" width="436" height="340">
              <fx:Script>
                        <![CDATA[
                                  [Bindable]public var url:String;
                                  protected function button1_clickHandler(event:MouseEvent):void
                                            // TODO Auto-generated method stub
                                            ml.unloadModule();
                        ]]>
              </fx:Script>
              <fx:Declarations>
                        <!-- Place non-visual elements (e.g., services, value objects) here -->
              </fx:Declarations>
              <s:ModuleLoader x="10" y="9" id="ml" url="{url}" width="404" height="277">
                        <s:unload>
                                  if(parent != null)
                                  parent.removeChild(this);
                        </s:unload>
              </s:ModuleLoader>
              <s:Button x="411" y="-23" width="17" height="16" label="Button"
                                    click="button1_clickHandler(event)" icon="assets/icon_close_down.png"/>
    </s:Panel>

    Instead of using an unload handler, just call both unloadModule and removeChild in the click handler.

  • ValueObjects memory - How can destroy when unload module

    The problem is when the app load and unload the same module, the data from callresponder is add to class R5objects. The ask is how can drop, delete, destroy,clean,..... this objects from memory when i unload the module. I try with System.gc () but i don't see change in memory.
    If i load and unload the same module many times the application take a lot of memory, the query to database take 500 rows and 10 fields
    Thanks
    T

    valueObjects only is created and used into the module, but when i unload the module valueObjects continue in memory, when i load the same module valueObjects take more and more memory
    I thought that when the module was unloaded all its objects are erased, you know how can drop or erase this type of object
    Cristian

  • Problems unloading modules (due to skins?)

    Hi,
    I have a problem in my Flex application where modules are not unloading. I moved the focus out, cleared out eventlisteners (I read diff. tutorials on that) and now modules are not increasing every time I load them but there is still always 1 instance of the module that has been loaded.
    Suppose we have a login module, if I would open it 5 times I would have 5 references in memory, now only 1 which is good, but when the module is not open it needs to be 0 and not 1. When I use the profiler I get 10 paths (this means references still in memory for the login module, right?) to the login module as displayed in the screenshot
    It seems to be an issue in the skins or how should I see this? Is it because the skins are used somewhere else in my app also? Can anyone shed some light on this?
    Thanks

    Which version of flex?
    Log a bug at http://bugs.adobe.com/jira with a small reproducible test case.
    -Gaurav
    http://www.gauravj.com/blog

  • Profiling the loading and unloading of modules

    Modules appear to be the ideal solution for building complex rich internet applications but first hand experience has also shown me that they can leak memory like nothing else. I've read anything and everything I could find about modules and module loading/unloading including of Alex Harui's blog post "What We Know About Unloading Modules" that reveals a number of potential leak causes that should be considered.
    I've now created a simple soak test that repeatedly loads and unloads a specified module to help identify memory leaks using the profiler. However, even with the most basic of modules, I find that memory usage will steadily grow. What I'd like to know is what memory stuff is unavoidable flex overhead associated with the loading of modules and what memory stuff am I guilty for, for not cleaning up object references? I'd like to be able to establish some baseline values to which I will be able to compare future modules against.
    I've been following the approach suggested in the Adobe Flash Builder 4 Reference page "Identifying problem areas"
    "One approach to identifying a memory leak is to first find a discrete set of steps that you can do over and over again with your application, where memory usage continues to grow. It is important to do that set of steps at least once in your application before taking the initial memory snapshot so that any cached objects or other instances are included in that snapshot."
    Obviously my set of discrete steps is the loading and unloading of a module. I load and unload the module once before taking a memory snapshot. Then I run my test that loads and unloads the module a large number of times and then take another snapshot.
    After running my test on a very basic module for 200 cycles I make the following observations in the profiler:
    Live Objects:
    Class
    Package (Filtered)
    Cumulative Instances
    Instances
    Cumulative Memory
    Memory
    _basicModule_mx_core_FlexModuleFactory
    201 (1.77%)
    201 (85.17%)
    111756 (24.35%)
    111756 (95.35%)
    What ever that _basicModule_mx_core_FlexModuleFactory class is, it's 201 instances end up accounting for over 95% of the memory in "Live Objects".
    Loitering Objects:
    Class
    Package
    Instances
    Memory
    Class
    600 (9.08%)
    2743074 (85.23%)
    _basicModule_mx_core_FlexModuleFactory
    200 (3.03%)
    111200 (3.45%)
    However this data suggests that the _basicModule_mx_core_FlexModuleFactory class is the least of my worries, only accounting for 3.45% of the total memory in "Loitering Objects". Compare that to the Class class with it's 600 instances consuming over 85% of the memory. Exploring the Class class deeper appears to show them all to be the [newclass] internal player actions.
    Allocation Trace:
    Method
    Package (Filtered)
    Cumulative Instances
    Self Instances
    Cumulative Memory
    Self Memory
    [newclass]
    1200 (1.39%)
    1200 (14.82%)
    2762274 (13.64%)
    2762274 (62.76%)
    This appears to confirm the observations from the "Loitering Objects" table, but do I have any influence over the internal player actions?
    So this brings me back to my original question:
    What memory stuff is unavoidable flex overhead associated with the loading of modules and what memory stuff am I guilty for, for not cleaning up object references? If these are the results for such a basic module, what can I really expect for a much more complex module? How can I make better sense of the profile data?
    This is my basic module soak tester (sorry about the code dump but there's not that much code really):
    basicModule.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Module xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/halo"
               layout="absolute" width="400" height="300"
               backgroundColor="#0096FF" backgroundAlpha="0.2">
         <s:Label x="165" y="135" text="basicModule" fontSize="20" fontWeight="bold"/>
    </mx:Module>
    moduleSoakTester.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/halo"
                   width="400" height="300" backgroundColor="#D4D4D4"
                   initialize="application_initializeHandler(event)">
         <fx:Script>
              <![CDATA[
                   import mx.events.FlexEvent;
                   import mx.events.ModuleEvent;
                   [Bindable]
                   public var loadCount:int = -1;
                   [Bindable]
                   public var unloadCount:int = -1;
                   public var maxCycles:int = 200;
                   public var loadTimer:Timer = new Timer(500, 1);
                   public var unloadTimer:Timer = new Timer(500, 1);
                   protected function application_initializeHandler(event:FlexEvent):void
                        loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, loadTimer_timerCompleteHandler);
                        unloadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, unloadTimer_timerCompleteHandler);
                   protected function loadModule():void
                        if(loadCount < maxCycles)
                             moduleLoader.url = [correctPath] + "/basicModule.swf";
                             moduleLoader.loadModule();
                             loadCount++;
                   protected function unloadModule():void
                        moduleLoader.unloadModule();
                        unloadCount++;
                   protected function load_clickHandler(event:MouseEvent):void
                        load.enabled = false;
                        loadModule();
                        unload.enabled = true;
                   protected function unload_clickHandler(event:MouseEvent):void
                        unload.enabled = false;
                        unloadModule();
                        run.enabled = true;
                   protected function run_clickHandler(event:MouseEvent):void
                        run.enabled = false;
                        moduleLoader.addEventListener(ModuleEvent.READY, moduleLoader_readyHandler);
                        moduleLoader.addEventListener(ModuleEvent.UNLOAD, moduleLoader_unloadHandler);
                        loadTimer.start();
                   protected function moduleLoader_readyHandler(event:ModuleEvent):void
                        unloadTimer.start();
                   protected function moduleLoader_unloadHandler(event:ModuleEvent):void
                        loadTimer.start();
                   protected function loadTimer_timerCompleteHandler(event:TimerEvent):void
                        loadModule();
                   protected function unloadTimer_timerCompleteHandler(event:TimerEvent):void
                        unloadModule();
              ]]>
         </fx:Script>
         <mx:ModuleLoader id="moduleLoader"/>
         <s:VGroup x="20" y="20">
              <s:HGroup>
                   <s:Button id="load" label="Load" click="load_clickHandler(event)" enabled="true"/>
                   <s:Button id="unload" label="Unload" click="unload_clickHandler(event)" enabled="false"/>
                   <s:Button id="run" label="Run" click="run_clickHandler(event)" enabled="false"/>
              </s:HGroup>
              <s:Label text="loaded: {loadCount.toString()}" fontSize="15"/>
              <s:Label text="unloaded: {unloadCount.toString()}" fontSize="15" x="484" y="472"/>
         </s:VGroup>
    </s:Application>
    Cheers,
    -Damon

    Easiest way I've found to get your SDK version from within Builder is to add this: <mx:Label text="{mx_internal::VERSION}" />
    http://blog.flexexamples.com/2008/10/29/determining-your-flex-sdk-version-number/
    Peter

  • How to load different modules in moduleLoader - some with other without unload?

    Ok so I've read a lot about modules and I decided to build a site where I have a button bar menu and a single moduleLoader, where all of my pages are separate modules. Some of the modules will be preloaded with moduleManager technique so they will be in memory and should pop up instantly and others should be unloaded since they will be used rarely. Imagine you have 50 pages, 45 of them use the same 3 modules and the rest 5 use 5 other modules.
    So I need 2 things:
    1) those 3 modules preloaded (loaded into memory) and then used - this is not a problem. In the change handler of the button bar I just set the url of the moduleLoader=""; and right after that line I put moduleLoader.url = "module1.swf" for example. This way the ready event fires everytime I change the selected button of the buttonBar and since the module is loaded into memory it changes immediately, which is great.
    2) I need the rest 5 modules that are not preloaded, to be loaded by the moduleLoader and when the user clicks on another button, the module to be unloaded and the new module for the new selected button to be loaded on it's place. So here unloading of the old module and loading of the new one should happen with 1 user interaction - clicking a button. How do I do that?
    I am asking this because I found out that there is some difference when the module has been preloaded or not which changes the way it unloads. Also in certain cases if a module has been unloaded once and loaded again it stops shooting the unload event by only changing the moduleLoader.url and then you have to specifically call moduleLoader.unloadModule() function to get it called.
    And all of this brought me to the idea that maybe the only way to make this work for case 2 is having moduleLoader.unloadModule(); and on the next line after it moduleLoader.url = "newModuleUrlHere";
    But then I bumped into a problem with flickering in my buttonBar selected button transition which I describe and give online example of here:
    http://forums.adobe.com/thread/760347?tstart=0
    So is there any technique of combining preloaded modules which should not be unloaded + the ones who need to be loaded and unloaded and all of this to be working with just one moduleLoader instance?
    I really didn't expect to have so much trouble with modules... If no one can suggest me a working example I will post each case I described here to help me get resolution to this cause I can't get on with my project and it's very important.
    Thanks in advance!

    Hi thanks for the reply here too
    I agree it totally makes sense if I do not unload modules to load them in the same application domain and not as a child. This way I wouldn't have to worry about the singletons I could have forgotten to initialize in the main application If my logic is correct. But still is it wrong to leave them in a child ApplicationDomain since I will still have modules I will need to unload and I would still have to be careful about the singleton managers?
    Note: have in mind I am trying to separate the module's from the main application, so the application won't use any classes defined in the modules since it won't be aware of what's in what module.
    Yes, I do have a buttonBar buttons which map to module urls.
    Ok I will try to setup my questions in a few very simple example applications, it would be easier for you to understand what's confusing me.
    http://filip.nedyalkov.net/moduleLoaderTesting2/ - view source enabled - look at testing3.mxml
    In the button bar change handler I have:
    moduleURL = buttonBar.
    selectedItem.url;moduleLoader.url = moduleURL;
    and I listen to the moduleLoader unload event.
    On the Unload Current Module Button I have: moduleLoader.unloadModule();
    Ok what is confusing me is this: When I start switching between module1 and module2 do they automatically get unloaded because I recall reading that changing the moduleLoader.url property doesn't unload the module just releases it? Also I'm getting the unload event shoot very strange because if I am on module1 and then click on module2 it doesn't shoot that module1 was unloaded, it doesn't do anything. As soon as I click back on module1 then it shoot unloaded (you can see that in my example in the text area).
    Another strange thing is that while doing this, everytime you click on module1 or module2 they get transferred over the network I can see that in mozilla firebug. Now if I am on module1 and click the Unload Current Module button the module really gets unloaded and then the unload event is correct and shoot when it's supposed to shoot. Now if you click on module2 and then come back to module1 it will get loaded again, but now it will be put in memory, it won't shoot unload event any more and it won't get transferred over the network when I switch the modules? Why is that ? All I did was unloading the module once and it changes everything.
    So I hope you undertstand this cause I have no idea is this supposed to work this way? Would you be so kind to explain me this behaviour ?
    Thanks!

  • Module not unloading if embedded font was ever used

    So, I have a test app that uses modules with the font embeded. Using ModuleManager I am able to load up the module. Once I call   IModuleInfo.factory.create(), I am then able to setStyle("fontFamily", "BPDiet") and the font does show up. The issue I am now having is that once I have used a font from a module, even if my TextArea is no longer using it (I even tried removing the textArea, and replacing it with a new one), the module will not unload.
    I read through this "What We Know About Unloading Modules" and I think I am not leaving any references around.They are loaded using the load() defaults. There is no code (that is used) in the module. The modules are not being added to the display, so they never receive focus.
    Note that I am unable to run the profiler as suggested in the article as I don't have the premium Flash Builder 4. <grrr>
    Note that the first module that is loaded, I can never get to unload, even if I never used the font embedded in it, but all subsequent modules will unload, if I do not use the embedded font. I can live with the first one being pinned as long as I can unload the others that are not in use.
    Here is the code from one of my modules:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Module xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx">
        <fx:Script>
            <![CDATA[
                import spark.components.TextArea;
                [Embed(source='assets/BPDiet.otf',
                        fontName='BPDiet',
                           mimeType='application/x-font')]
                public static var BPDietNormal:Class;
                public function GetSampleTextArea():TextArea {
                    var SampleTextArea:TextArea = new TextArea();
                    SampleTextArea.text = "Test BPDiet please!";
                    SampleTextArea.setStyle("fontFamily", 'BPDiet');
                    return SampleTextArea;           
            ]]>
        </fx:Script>
    </mx:Module>
    And here is the App that is loading and using the modules:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="400" minHeight="400">
        <fx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                import mx.core.UIComponent;
                import mx.events.FlexEvent;
                import mx.events.ModuleEvent;
                import mx.managers.SystemManager;
                import mx.modules.IModule;
                import mx.modules.IModuleInfo;
                import mx.modules.Module;
                import mx.modules.ModuleManager;
                import spark.components.TextArea;
                private var _ta:TextArea = null;
                protected var _moduleInfo:IModuleInfo;
                private function LoadFontTextArea(fontSwf:String):void {
                    status.text = "Loading the font pack";
                    _moduleInfo = ModuleManager.getModule(fontSwf);
                    // add some listeners
                    _moduleInfo.addEventListener(ModuleEvent.READY, onModuleReady);
                    _moduleInfo.addEventListener(ModuleEvent.ERROR, moduleLoadErrorHandler);
                    _moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleUnloadHandler);
                    _moduleInfo.load();
                private function onModuleReady(event:ModuleEvent):void {
                    status.text = "The font pack swf Ready \n" + event.module.url;
                    //All I had todo was create the module, then I could access the embeded font by name
                    var fontMod:* = event.module.factory.create();
                    //_ta = fontMod.GetSampleTextArea();
                    //panelToStuff.addElement(_ta);
                    fontMod = null;
                    //fontNameForSample = event.module.url.replace(".swf", "");
                private function moduleLoadErrorHandler(event:ModuleEvent):void {
                    status.text = "Font Module Load Error. \n" +
                        event.module.url + "\n"+ event.errorText;
                private function moduleUnloadHandler(event:ModuleEvent):void {
                    status.text = "Font Module Unload Event. \n" + event.module.url;
                private function fontChangedHandler():void {
                    unloadCurrentFont();
                    LoadFontTextArea(String(availFonts.selectedItem));
                private function unloadCurrentFont():void {
                    if (_ta != null) {
                        panelToStuff.removeElement(_ta);
                        _ta = null;
                    panelToStuff.removeElement(sampleTextArea);
                    sampleTextArea = null;
                    sampleTextArea = new TextArea();
                    sampleTextArea.id = "sampleTextArea";
                    sampleTextArea.text = "Some text for your viewing pleasure. " + colorForBK.toString(16);
                    panelToStuff.addElement(sampleTextArea);               
                    if (_moduleInfo != null)
                        _moduleInfo.release();
                        //_moduleInfo.unload();
                        _moduleInfo = null;
                    System.gc();
                private function DoNonImportantWork():void {
                    colorForBK -= 0xFAA;
                    if (colorForBK < 0x0) colorForBK = 0xFFFFFF;
                    var foo:* = {prop1: "yea" + colorForBK.toString(), prop2:"boo" + colorForBK.toString()};
                    var hmm:String = foo.prop1 + " " + foo.prop2;
                    regedFonts = new ArrayCollection(Font.enumerateFonts(false));
                [Bindable]
                private var colorForBK:int = 0xFFFFFF;
                [Bindable]
                private var fonts:ArrayCollection =
                    new ArrayCollection(new Array("AlexandriaFLF.swf", "BPDiet.swf", "ChanpagneFont.swf", "KidsFont.swf"));
                [Bindable]
                private var regedFonts:ArrayCollection;
                [Bindable]
                private var fontNameForSample:String = "";
            ]]>
        </fx:Script>
        <s:VGroup id="panelToStuff">
            <s:HGroup>
                <s:Label id="status" text="status area" backgroundColor="{colorForBK}"/>
                <s:VGroup>
                    <s:DropDownList id="availFonts" dataProvider="{fonts}" change="fontChangedHandler()" />
                    <s:Button label="UnLoad" enabled="true" click="unloadCurrentFont()"/>
                    <s:Button label="doSome" enabled="true" click="DoNonImportantWork()"/>
                </s:VGroup>
            </s:HGroup>
            <s:HGroup>
                <s:Button click="fontNameForSample = 'BPDiet';" label="BPDiet"/>
                <s:Button click="fontNameForSample = 'Champagne';" label="Champagne"/>
                <s:Button click="fontNameForSample = 'Kids';" label="Kids"/>
            </s:HGroup>
            <s:Label text="{regedFonts.length} reg'ed"/>
            <s:TextArea id="sampleTextArea" fontFamily="{fontNameForSample}" text="Some Sample text for your viewing"/>
        </s:VGroup>
    </s:Application>
    A couple things to note; I am calling System.rc() in the unloadCurrentFont() method just to speed up seeing the SWF unload in the debug console. The DoNonImportantWork() is there to just cause some events to happen and to create some objects that will need to be GC'ed. It also let me know that the fonts are not getting registered in Font.
    I'm going to have 30 fonts (and more, that designer is busy) that I will need to be able to dynamically load, but right now, loading them with CSS style modules blows up after about 15 because style modules register the font so I cannot unload the CSS swf.

    To help eliminate the question of whether the TextArea is being held by something else, I have removed it from the MXML, and now programatically create it. That did not help.
    So, I got the trial version of Flash Builder 4 installed on another machine in the office so that I can use the profiler. (The profiler is pretty cool by the way).
    After a lot of profiing, I found four paths to the module's FlexModuleFactory.
    Two of those paths go to EmbeddedFontRegistry, whose data is static. I could get into it and remove font entry and free up the moduleFactory from there. This is a hack, that entry in/on EmbeddedFontRegistry.font should have been cleaned up by the code removing the fontFamily from the TextArea. (Note that EmbeddedFontRegistry is marked [ExcludeClass], which I assume means I should not really be messing with it.
    The other two I cannot get to as they are anonymous. They also don't appear to be referenced, as the Object References shows them both as GC root objects. Here is a screen shot:
    I did a search through the sdk code and 'fbs' only shows up as a parameter on the init function of various Marshal support classes, but is not used in the init()
    Anyway, these references to the FlexModuleFactory do not get held if I do not use the embeded font in the module.
    Here is the updated code:
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                   xmlns:s="library://ns.adobe.com/flex/spark"
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="400" minHeight="400">
        <fx:Script>
            <![CDATA[
                import mx.collections.ArrayCollection;
                import mx.core.EmbeddedFont;
                import mx.core.EmbeddedFontRegistry;
                import mx.core.IEmbeddedFontRegistry;
                import mx.core.UIComponent;
                import mx.events.FlexEvent;
                import mx.events.ModuleEvent;
                import mx.managers.SystemManager;
                import mx.modules.IModule;
                import mx.modules.IModuleInfo;
                import mx.modules.Module;
                import mx.modules.ModuleManager;
                import spark.components.TextArea;
                private var _ta:TextArea = null;
                protected var _moduleInfo:IModuleInfo;
                private function LoadFontTextArea(fontSwf:String):void {
                    status.text = "Loading the font pack";
                    _moduleInfo = ModuleManager.getModule(fontSwf);
                    // add some listeners
                    _moduleInfo.addEventListener(ModuleEvent.READY, onModuleReady);
                    _moduleInfo.addEventListener(ModuleEvent.ERROR, moduleLoadErrorHandler);
                    _moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleUnloadHandler);
                    _moduleInfo.load();
                private function onModuleReady(event:ModuleEvent):void {
                    status.text = "The font pack swf Ready \n" + event.module.url;
                    //All I had todo was create the module, then I could access the embeded font by name
                    var fontMod:* = event.module.factory.create();
                    fontMod = null;
                private function moduleLoadErrorHandler(event:ModuleEvent):void {
                    status.text = "Font Module Load Error. \n" +
                        event.module.url + "\n"+ event.errorText;
                private function moduleUnloadHandler(event:ModuleEvent):void {
                    status.text = "Font Module Unload Event. \n" + event.module.url;
                private function fontChangedHandler():void {
                    unloadCurrentFont();
                    LoadFontTextArea(String(availFonts.selectedItem));
                private function unloadCurrentFont():void {
                    if (_ta != null && _moduleInfo != null) {
                        var fontName:String = _ta.getStyle("fontFamily");
                        _ta.setStyle("fontFamily", "");
                        _ta.validateProperties();
                        if (_ta.textDisplay) {
                            _ta.textDisplay.validateProperties();
                        panelToStuff.removeElement(_ta);               
                        _ta = null;
                        //This I should not have to do, but the framework is not doing it
                        var embFontReg:IEmbeddedFontRegistry = EmbeddedFontRegistry.getInstance();
                        var embFonts:Array = embFontReg.getFonts();
                        for each (var curEmbFont:EmbeddedFont in embFonts){
                            if (curEmbFont.fontName == fontName){
                                embFontReg.deregisterFont(curEmbFont, _moduleInfo.factory);
                    if (_moduleInfo != null)
                        _moduleInfo.unload();
                        _moduleInfo = null;
                    System.gc();
                private function AddTA():void {
                    _ta = new TextArea();
                    _ta.text = "Some text for your viewing pleasure. " + colorForBK.toString(16);
                    panelToStuff.addElement(_ta);
                private function DoNonImportantWork():void {
                    colorForBK -= 0xFAA;
                    if (colorForBK < 0x0) colorForBK = 0xFFFFFF;
                    var foo:* = {prop1: "yea" + colorForBK.toString(), prop2:"boo" + colorForBK.toString()};
                    var hmm:String = foo.prop1 + " " + foo.prop2;
                [Bindable]
                private var colorForBK:int = 0xFFFFFF;
                [Bindable]
                private var fonts:ArrayCollection =
                    new ArrayCollection(new Array("AlexandriaFLF.swf", "BPDiet.swf", "ChanpagneFont.swf", "KidsFont.swf"));
            ]]>
        </fx:Script>
        <s:VGroup id="panelToStuff">
            <s:HGroup>
                <s:Label id="status" text="status area" backgroundColor="{colorForBK}"/>
                <s:VGroup>
                    <s:DropDownList id="availFonts" dataProvider="{fonts}" change="fontChangedHandler()" />
                    <s:Button label="UnLoad" enabled="true" click="unloadCurrentFont()"/>
                    <s:Button label="AddTA" enabled="true" click="AddTA()"/>
                    <s:Button label="doSome" enabled="true" click="DoNonImportantWork()"/>
                </s:VGroup>
            </s:HGroup>
            <s:Button click="_ta.setStyle('fontFamily', 'BPDiet');" label="BPDiet"/>
        </s:VGroup>
    </s:Application>
    I really think I've reached the end of what I can do. This really seems like a bug.

  • How to unload dynamically loaded modules?

    Hi,
    I have a problem with unloading module, which I loads dynamically.
    Here is a fragment my code:
    <TitledWindow .......creationComplete="init()"/>
    <mx:Accordion id="lista_ryzyk">
    </mx:Accordion>
    <mx:Script>
    public function init():void
    {    CairngormEventDispatcher.getInstance().addEventListener(LoadRisksEvent.EVENT_RESULT, populateAccordion);
    public function populateAccordion(event:CairngormEvent):void
         lista_ryzyk.removeAllChildern();
         for (i in risks)
              var m:ModuleLoader = new ModuleLoader();
              m.url = path_to_module;
              m.label = module_label;
              m.loadModule();
         lista_ryzyk.addChildAt(m,Number(i));
    </mx:Script>
    The modules loads fine. Each module adds own eventListener for some event. It works fine, but ONLY for first time. For next invoke populateAccordion function, the modules loads, but don't reacts for event. I investigate !!! that for events reacts that modules, which was loaded for the first time!!! How to remove it????

    Using array, didn't solve my problem, but it is possible that I'm doing something wrong.
    I still can't catch event in second time loaded module :-((( I have tried to solve this problem from wednesday! it goes me crazy!
    Could you, or anybody, try to inspect my code and help me? I have no idea how to manage it.
    I know exactly what is wrong, but I can't improve that. In module's creationComplete function I display the UID of this module, and in body of eventHandler function I do the same. In case of FIRST time  the displayed UID are the same, but when I load the module second time, the UID of the loaded module displayed in creationComplete function is new, but the UID displayed in handler function is the same as the first loaded module. So my event is catch by the wrong modul, and I don'tknow how to change it, how to process event in my newly loaded module.

Maybe you are looking for