Garbage-collecting the cloned objects

public class Clone implements Cloneable {
public static void main(String[] arg) {
Clone i0, i1;
i0 = new Clone();
System.out.println("Created: " + i0);
try{
i1 = (Clone)i0.clone();
System.out.println("Cloned: " + i1);
} catch(CloneNotSupportedException e){
e.printStackTrace();
i0 = null;
i1 = null;
System.gc();
public Object clone() throws CloneNotSupportedException {
return super.clone();
public void finalize() {
System.out.println("Finalizing " + this);
With the example above you can notify that with Hotspot VM of JDK1.3 the
finalize() method will not be called for the cloned object; though,
running the sample with the classic VM, the finalize() will be
called for both objects.
Bypassing the finalize() can be made intended, in order to avoid
multiple "release" or "close" calls on the same object, eg. if the
finalize() has to close a file or a JDBC-connnection. But then why
is it called in the classic VM? Is it sure that the cloned object
too will be garbage-collected?

Here's the proper way to write a clone() method:
public Object clone() {
    try {
        return super.clone();
    } catch (CloneNotSupportedException e) {
        throw new RuntimeException(e);
}There's no reason for a clone() method to declare that it throws CloneNotSupportedException. Doing so just makes code that uses the clone() method more complicated unnecessarily.
Here's the proper way to write a finalizer:
protected void finalize() {
    try {
        // perform subclass cleanup
    } finally {
        super.finalize();
You should always make finalize() protected to help ensure that only the garbage collector calls it, and it should always call super.finalize() to ensure that the superclass finalization can happen.
Now, to your question. There's no way to guarantee that an object will be garbage collected or finalized. In fact, finalizers are so notoriously hard to write correctly that Java 2 added PhantomReferences to allow a simpler way to clean up objects.
If you want an object to release resources, such as closing a file or releasing a database connection, provide a close() or dispose() or release() method in the class and close the resources there. Even if you could guarantee that your finalizer is called or if you used PhantomReference queues to perform cleanup, this cleanup would probably not happen in a timely manner. Finalizers are not C++ destructors -- if you need to release resources, add a method to do that.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • CORBA & Garbage Collection of Remote Objects

    Hi!
    I see lots of stuff on this topic for RMI. However I did not see much on garbage collection of remote objects using CORBA.
    My question is: once I pass a reference to a CORBA client, how can I make sure that these references are garbage collected once the client application is done with them?
    Another question is what happens to all remote object references if the client application crashes? Is there anyway for the server to be notifed and ensure that memory is claimed by the garbage collector?
    Of course that if these references are just left hanging over, memory leaks can be a problem ...
    Any help would be appreciated.
    Regards,
    Jo�o

    These are questions I've been wondering about for some time too.... Does anyone has a hint?

  • Premature Garbage Collection of Remote Objects

    I have a problem with distributed garbage collection and RMI. In CSPoker we try to support RMI for client-server communication. The client looks up the server through the registry, calls the login method and receives back a Remote Object reference called ServerContext. The client can register Remote even listener Objects with the server.
    In both directions we occasionally see:
    java.rmi.NoSuchObjectException: no such object in table
    The behaviour is completely unpredictable. Some developers never see it, others see it all the time. Even on the same machine, sometimes it failes immediately
    and sometimes it fails after a while. One person running the Sun JRE 6 on Windows has this poblem most frequently.
    Can this be a bug or do we misinterpret something? The way we see it, as long as the client leases the Remote Object it shouldn't be GCed. All tests are run on localhost so no network partition can occur.
    The problem would probably be solved if we hold static references to all Remote Objects in the local JVM. This is not an option because we want the Objects to be GCed once the lease expires.
    Here are 2 debugging outputs of server runs with RMI logging enabled:
    http://cspoker.pastebin.com/f27a7d6fc
    As you can see, the lease requests are coming through but a NoSuchObjectException is thrown and the Object is finalized.
    http://cspoker.pastebin.com/f732797d2

    Thanks for the quick reply.
    For instance:
    11:56:02,427 DEBUG (org.cspoker.common.api.shared.context.ForwardingRemoteServerContext.java:72) [finalize] - Garbage collecting old context: org.cspoker.server.rmi.export.ExportingServerContext@15a8767
    07.11.2008 11:56:02 sun.rmi.server.UnicastServerRef logCall
    FEINER: RMI TCP Connection(2)-10.0.4.106: [10.0.4.106: sun.rmi.transport.DGCImpl[0:0:0, 2]: java.rmi.dgc.Lease dirty(java.rmi.server.ObjID[], long, java.rmi.dgc.Lease)]
    07.11.2008 11:56:03 sun.rmi.transport.Transport serviceCall
    FEIN: RMI TCP Connection(2)-10.0.4.106: [10.0.4.106] exception:
    java.rmi.NoSuchObjectException: no such object in table
            at sun.rmi.transport.Transport.serviceCall(Transport.java:129)
            at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:466)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:707)
            at java.lang.Thread.run(Thread.java:595)The context Object is exported and returned to the client here :
    return (ExternalRemoteServerContext) UnicastRemoteObject.exportObject(context, 0);Then [the object|http://code.google.com/p/cspoker/source/browse/trunk/server/rmi/src/main/java/org/cspoker/server/rmi/export/ExportingServerContext.java?r=1023] that was just exported is GCed.
    11:56:02,427 DEBUG (org.cspoker.common.api.shared.context.ForwardingRemoteServerContext.java:72) [finalize] - Garbage collecting old context: org.cspoker.server.rmi.export.ExportingServerContext@15a8767Then a lease request comes in:
    FEINER: RMI TCP Connection(2)-10.0.4.106: [10.0.4.106: sun.rmi.transport.DGCImpl[0:0:0, 2]: java.rmi.dgc.Lease dirty(java.rmi.server.ObjID[], long, java.rmi.dgc.Lease)]Then the client calls a method on the remote object and the NoSuchObjectException is thrown.
    The behaviour is non-deterministic in any case but yes, on the Linux JVM I'm not seeing the problem, somebody on Windows gets it all the time.

  • Garbage Collection: how many objects are created after for loop?

    Please see the fallowing java code
    1 public class Test1 {
    2     
    3     public static void main(String[] args) {
    4          
    5          MyObj obj = null;
    6          for(int i=0;i<5;i++){
    7               obj = new MyObj();
    8          }
    9 // do something
    10
    11     }
    12 }
    so my question is How may objects are eligible for garbage collection at line no: 9 (// do something)?

    so my question is How may objects are eligible for
    garbage collection at line no: 9 (// do something)?It's impossible to answer that question since we don't know how MyObj is implemented.
    Kaj

  • Regarding collecting the BW objects through the transport conn- in backend

    Hi All,
    I am trying to collect all the In data flow afterwards objects of a cube through the transport connection.
    But it is more time as a result I am unable to retrive the result because of system timeout.
    My question is, is there any way to perform the abovementioned function in the backend. If yes, how exactly.
    Thanks with regards,
    Vinay H.S

    Hi Murali,
    Thanks a lot for the response.
    I have checked it for the Info Object and it is in the respective package. But,the data elements and domains are still in $TMP .
    Regards,
    Manjari.

  • Static class garbage collection

    Can garbage collector can garbage collect static classes ?.
    My doubt is that when you access a static class , that class is loaded through its class loader ( when first time that class is referenced ).
    So when did the garbage collector collects this static class ( assume that static class no longer referred ).
    Please do more information,
    What are the ways to prevent garbage collector for a particular class ( Assume that i m implementing a singleton for my java runtime)
    thanks and regards
    Renjith.

    Can garbage collector can garbage collect static classes ?. Static classes are nothing special in terms of class loading - they are only different in visibility for linking.
    Perhaps you mean static members of classes?
    My doubt is that when you access a static class ,
    that class is loaded through its class loader ( when
    first time that class is referenced ). Classes are always loaded through classloaders. Objects of those classes are allocated from the heap, and the object instances refer to the class object.
    Objects (either instances, or classes themselves) are garbage collected when they are no longer live (i.e. no live object refers to them). (This is a somewhat recursive definition, and sometimes, you can have cyclic dependencies that make garbage collection tricky, but the GC, while it has to be conservative for correctness, usually gets it right).
    So for a static member to be garbage-collected, the class has to be garbage-collected first. The class cannot be GC'ed until all references to it go away (this includes all dynamically allocated objects of that type, and the class loader that loaded that class).
    And yes, class loaders can go away, but only if they are created by your program. The system class loader (which is the default classloader you get if you don't create any class loaders of your own) never goes away, so any class loaded from CLASSPATH will never be unloaded.
    (As an example, servlet containers - e.g. Tomcat, Weblogic, etc.) allocate one or more classloaders for each webapp. When the webapp is un-deployed, the classloaders are "orphaned", and they, and any classes loaded by them (from the WEB-INF/lib and WEB-INF/classes directories) are unloaded and garbage-collected. (After all the dynamic objects of those classes are GC'ed, of course).
    >
    So when did the garbage collector collects this
    static class ( assume that static class no longer
    referred ).
    Please do more information,
    What are the ways to prevent garbage collector for a
    particular class ( Assume that i m implementing a
    singleton for my java runtime)
    thanks and regards
    Renjith.

  • Array garbage collection

    I need to keep track of what objects got garbage collected in a program.
    So I made sure that the classes of interest have a 'finalize()' method that simply print out the toString() and reference of the garbage collected object (using System.identityHashCode(this)).
    This worked fine for all objects except arrays.
    I went as far as substituting my own version of java.lang.Object that has an appropriate finalize(), but still no finalize() method seem to be getting called when an array object is 'supposed' to be garbage collected (the process consumes most of the system memory...)
    Any thoughts?
    Thanks,
    Wes

    Just an idea. You can try using WeakReference. Rather than using finalize, you can use the clear method of Reference.
    Here is some pseudo code
    .. class GCWatcher{
    List wrl = ...
    public void watch(Object obj){
    wrl.add(new WatchableWeakReference(obj));
    .. class WatchableWeakReference{
    WathableWeakReference(Object obj){
    super(obj);
    public void clear(){
    wrl.remove(this);
    Object obj = get();
    print out your message
    super.clear();
    If you try it let me know if it worked.

  • Disabling RMI Explicit Garbage Collection

    I have an application that uses RMI. From different articles on the javasoft web site, I have read that RMI explicitly does a Full RMI every minute (default setting). This is undesirable, b/c these full GCs are causing some objects I need to use later to be garbage collected. From the site, the options are to:
    1) Disable Full GC
    2) Delay Full GC
    For point 1), what are the consequences of disabling explicit full GCing that RMI does? Documentation on the javasoft website only says that "this may also cause some objects to take much longer to be reclaimed" etc. To me, I would think that disabling the explicit Full GC is a bad idea for RMI applications (unless they are really short lived, but that is not my case). It would seem safer to go with 2) option to delay the Full GCs since it's not entirely clear what the consequences are of completey disabling explicit GCs, but this still causes objects I still need to use later to be garbage collected. The last option which I feel is not very elegant, would be to just set something to reference or use that object that is being gc'ed so when a Full GC is performed it doesn't get cleaned up. Does anyone have any experience with this or have any better suggestions?
    I am using Java 1.4.2 currently, but am also interested in learning what would be good for Java 1.2.X and 1.3.X as well.
    Thanks!
    These are the links that I have already visited or docs that I have already read on this topic:
    1) Java 2 Platform, Standard Edition v 1.4 Performance and Scalability Guide
    http://java.sun.com/j2se/1.4/performance.guide.html
    2) Frequently Asked Questions about Garbage Collection in the HotspotTM JavaTM Virtual Machine
    http://java.sun.com/docs/hotspot/gc1.4.2/faq.html
    3) Improving Java Application Performance and Scalability by Reducing Garbage Collection Times and Sizing Memory Using JDK 1.4.1
    http://developers.sun.com/techtopics/mobility/midp/articles/garbagecollection2/#11.1.3.15
    4) Garbage Collection for Remote Objects (1.4.2)
    http://java.sun.com/j2se/1.4.2/docs/guide/rmi/spec/rmi-arch4.html

    Towards the end of my pot I wrote:
    The last option which I feel is not very elegant, would be to just set something to reference or use that object that is being gc'ed so when a Full GC is performed it doesn't get cleaned up. Does anyone have any experience with this or have any better suggestions?
    I realize that I can reference these objects, but I don't think that is really a great solution. This would mean deliberately referencing them (a hack at a solution in my view) when really it's the explicity GC running every minute (b/c of RMI) that is collecting them. If I turn the explicit GC off, my objects are not collected like this.
    My question was really does anyone have any better ideas or experience with RMI's explicit garbage collecting? I don't need to read a tutorial to tell me how to keep my objects alive by referencing them. Thanks.

  • Garbage Collection cannot cope?

    Pretty sure this is not the case but after reading articles saying nulling objects in HashMaps is expensive I need to find a way of getting my HashMaps collected.
    My webapp uses Quartz and a worker thread launched by Quartz runs some code that caches up to 1.5 million key value pairs in a HashMap. Believe me this is faster than going to the database several hundred thousand times to lookup. But just before the task finishes I call clear() on the HashMap and then set it to null.
    However a separate task follows that does a similar thing with a different set of key value pairs in the HashMap. The first set are not collected. And so on until by the 4th one to run I run out of the 4GB of RAM I have allocated to Tomcat, in which all this runs. So it appears to me that it never gets a chance to collect the value objects from the HashMap. I smy only option to loop through all entries in the HashMap nulling both key and value?
    Thx.
    David

    1) The garbage collector can cope just fine thanks.
    2) Setting things to null is dumb and pointless
    3) Your design has some major flaws.
    That said the real issue here is that you are leaking memory. You'll have to address that. The garbage collector will release memory held by objects that do not have any references. Your's apparently do (likely) or you have previously configured the garbage collector in some way to make it incompatible with your needs (unlikely)
    You will probably not like anything I have had to say but I would encourage you to know that setting anything to null isn't a solution for anything.

  • RE unregistering an event listener so it can be garbage-collected

    One good practice in AS 3 is: When you register and event listener with an object, be sure your program also eventually unregisters that listener.
    So, let's say you created an <mx:RemoteObject> and the result listener did its job; you now have the data in an ArrayCollection or something, so you don't need the listener any longer.
    Question: how do you now unregister that result listener?
    Carlos

    That good practice only really applies to long-lived objects with short-lived listeners. Typically, when you are declaring a listener in MXML, it will be a method of your MXML component, so it will not be garbage collected anyway until your component is garbage collected. Normally, this is fine--there is no need to micro-manage the garbage collector unless your listener needs to allocate massive amounts of memory for whatever reason.
    If you really want to do this anyway, you can register the listener as an anonymous function and then call something like
    idOfRemoteObject.removeEventListener(ResultEvent.RESULT, arguments.callee);
    in the listener, but I think this is overkill. When your app is done with the component and the component is elligible for garbage collection, the listener will go with it.

  • DocumentBuilderFactory.newInstance() only works after garbage collection

    Hi all,
    I am stucked with a strange behaviour of "DocumentBuilderFactory.newInstance()".
    I use the DocumentBuilderFactory in an applet
    to parse an xml-file.
    My applet starts ok until the line 5 (newInstance) gets called.
    At this time it seems that nothing happens anymore and that
    the applet fails to continue.
    But when I open up the java console and hit
    g (garbage collection) the xml parsing continues immediatly
    and my applet completes loading and runs ok.
    1 private void genarteDomNodes() {
    2 try {
    3 // ---- Parse XML file ----
    4 DocumentBuilderFactory factory =
    5 DocumentBuilderFactory.newInstance();
    6 DocumentBuilder builder =
    7 factory.newDocumentBuilder();
    8 Document document = builder.parse(
    9 new URL(this.myModules_xml).openStream() );
    10 // ---- Get list of nodes to given element tag name ----
    11 NodeList ndList =
    12 document.getElementsByTagName("meter-group");
    13 printNodesFromList( ndList );
    14 } catch( SAXParseException spe ) {
    15 ...
    16 } catch( SAXException sxe ) {
    17 ...
    18 } catch( ParserConfigurationException pce ) {
    19 ...
    20 } catch( IOException ioe ) {
    21 ...
    22 }
    23 }

    I am still stucked with this problem. But I found out how to enable JAXP debug output for applets (setting system properties isn't allowed for applets).
    This puts somemore output to the java console. It might help someone to understand my problem. I also printed some debug messages to track down my problem.
    Following is the console output of my applet:
    URL of XML to parse = "http://10.110.132.195/c8000-modules.xml"
    entering "genarteDomNodes"
    just before calling "DocumentBuilderFactory.newInstance()"
    JAXP: find factoryId =javax.xml.parsers.DocumentBuilderFactory
    !!! at this time the applet "hangs" and nothing happens;
    until I hit the "g" button. Then applet continues immediatly and prints:
    JAXP: loaded from fallback value: com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
    JAXP: created new instance of class com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl using ClassLoader: sun.plugin.security.PluginClassLoader@32060c
    After invoking the garbage collector the applet continue to parse the xml file and runs as expected.
    Can someone help me please.

  • Help with Cloned Objects

    Object.clone() should create a new Instance of the Object right? Same member varible values, etc. but different memory, not a reference back to the same Object right?
    I've got the following class that implements Cloneable:
    public abstract class Control implements ControlInterface, Cloneable {
       * Create a clone from super.clone() and add it to the List this.clones
      public Object clone()  {
        Control ctrl = null;
        System.out.println("Orig : " + this.getMeta("id") + "," + this.toString());
        try {
          ctrl = (Control)super.clone();
          clones.add(ctrl);
          // change the Control's ID to reflect it's
          // position in the List
          ctrl.setMeta("id", ctrl.getMeta("id") + "_" + clones.size());
          System.out.println("Clone: " + ctrl.getMeta("id") + "," + ctrl.toString());
          System.out.println("Orig : " + this.getMeta("id") + "," + this.toString());
        catch (CloneNotSupportedException e) {
          // should never happen since class implements Cloneable
        return ctrl;
    }When I clone the object, it prints:
    Orig : companyname,com.alcatel.report.controls.TextControl@ca5f2c
    Clone: companyname_1,com.alcatel.report.controls.TextControl@2e714b
    Orig : companyname_1,com.alcatel.report.controls.TextControl@ca5f2c
    Why does the original Object's getMeta("id") value change? Shouldn't it stay the same? Ugh, I'm confused :)

    right, sorry - I mean, could you post the code where
    you create the original object, then the cloned
    object.Well, nothing really non-standard about it, just a call to the constructor and then a call to the .clone() method later:
    creation
      private void parseControls(Node node) throws AlaException, AlaMissingParamException {
        if (node != null) {
          NodeList children = node.getChildNodes();
          for (int i=0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if ("input".equals(child.getNodeName())) {
              NamedNodeMap attribs = child.getAttributes();
              Node type = attribs.getNamedItem("type");
              if ("text".equals(type.getNodeValue())) {
                this.controls.add(new TextControl(child, request));
              if ("search".equals(type.getNodeValue())) {
                this.controls.add(new SearchControl(child, request));
              if ("date".equals(type.getNodeValue())) {
                this.controls.add(new DateControl(child, request));
              if ("date-range".equals(type.getNodeValue())) {
                this.controls.add(new DateRangeControl(child, request));
              if ("lov".equals(type.getNodeValue())) {
                this.controls.add(new LovControl(child, request));
    clone
      public void cloneControl(String id) throws AlaException {
        for (int i=0; i < controls.size(); i++) {
          Control ctrl = (Control)controls.get(i);
          if (ctrl.getMeta("id").equals(id)) {
            ctrl.clone();
      }The returned Object is not saved because the controls keep track of their own clones in an ArrayList.

  • Xcode 3 Garbage collection

    Hi
    I have series of questions about Garbage collection and Xcode.
    I have read apples GC guide but I still don’t really understand how to use garbage collection.
    1. How do I enable GC in Xcode 3? I can’t find the -fobjc-gc flag under the build panel.
    2. Do didReceiveMemoryWarning have any meaning in a garbage collected environment? Should I try to close any unnecessary resources.
    3. Can/should I skip all release and dealloc code?

    If you're running on the iPhone, you can't use garbage collection; the memory-managed (release/retain) model is your only option. (If you're not running on the iPhone, there are no memory warnings, unless I'm mistaken.)

  • When will the demo object be eleigible for garbage collection?

    class Test {
         private Demo d;
         void start() {
         d = new Demo();
         this.takeDemo(d);
         void takeDemo(Demo demo) {
         demo = null;
         demo = new Demo();
         }

    Hey flounder, I am myself confused about garbage collection and assertions (yesterday)... Anyway because of ur interest in answering my query, I'll give one more try... But, if it's wrong, Please help me out.
    The Demo (not demo) object created at line 4 has one 'this' reference on the next line. And as soon as this reference is eleigible, I guess even Demo d will be eligible. Correct?

  • Remove / unload external swf file(s) from the main flash file and load a new swf file and garbage collection from memory.

    I can't seem to remove / unload the external swf files e.g when the carousel.swf (portfolio) is displayed and I press the about button the about content is overlapping the carousel (portfolio) . How can I remove / unload an external swf file from the main flash file and load a new swf file, while at the same time removing garbage collection from memory?
    This is the error message(s) I am receiving: "TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/removeChild()
    at index_fla::MainTimeline/Down3()"
    import nl.demonsters.debugger.MonsterDebugger;
    var d:MonsterDebugger=new MonsterDebugger(this);
    stage.scaleMode=StageScaleMode.NO_SCALE;
    stage.align=StageAlign.TOP_LEFT;
    stage.addEventListener(Event.RESIZE, resizeHandler);
    // loader is the loader for portfolio page swf
    var loader:Loader;
    var loader2:Loader;
    var loader3:Loader;
    var loader1:Loader;
    //  resize content
    function resizeHandler(event:Event):void {
        // resizes portfolio page to center
    loader.x = (stage.stageWidth - loader.width) * .5;
    loader.y = (stage.stageHeight - loader.height) * .5;
    // resizes about page to center
    loader3.x = (stage.stageWidth - 482) * .5 - 260;
    loader3.y = (stage.stageHeight - 492) * .5 - 140;
    /*loader2.x = (stage.stageWidth - 658.65) * .5;
    loader2.y = (stage.stageHeight - 551.45) * .5;*/
    addEventListener(Event.ENTER_FRAME, onEnterFrame,false, 0, true);
    function onEnterFrame(ev:Event):void {
    var requesterb:URLRequest=new URLRequest("carouselLoader.swf");
    loader = null;
    loader = new Loader();
    loader.name ="carousel1"
    //adds gallery.swf to stage at begining of movie
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
    function ioError(event:IOErrorEvent):void {
    trace(event);
    try {
    loader.load(requesterb);
    } catch (error:SecurityError) {
    trace(error);
    addChild(loader);
    loader.x = (stage.stageWidth - 739) * .5;
    loader.y = (stage.stageHeight - 500) * .5;
    // stop gallery.swf from duplication over and over again on enter frame
    removeEventListener(Event.ENTER_FRAME, onEnterFrame);
    //PORTFOLIO BUTTON
    //adds eventlistner so that gallery.swf can be loaded
    MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
    function Down(event:MouseEvent):void {
    // re adds listener for contact.swf and about.swf
    MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
    MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
    //unloads gallery.swf from enter frame if users presses portfolio button in nav
    var requester:URLRequest=new URLRequest("carouselLoader.swf");
        loader = null;
    loader = new Loader();
    loader.name ="carousel"
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
    function ioError(event:IOErrorEvent):void {
    trace(event);
    try {
    loader.load(requester);
    } catch (error:SecurityError) {
    trace(error);
    addChild(loader);
    loader.x = (stage.stageWidth - 739) * .5;
    loader.y = (stage.stageHeight - 500) * .5;
    removeChild( getChildByName("about") );
    removeChild( getChildByName("carousel1") );
    // remove eventlistner and prevents duplication of gallery.swf
    MovieClip(root).nav.portfolio.removeEventListener(MouseEvent.MOUSE_DOWN, Down);
    //INFORMATION BUTTON
    //adds eventlistner so that info.swf can be loaded
    MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
    function Down1(event:MouseEvent):void {
    //this re-adds the EventListener for portfolio so that end user can view again if they wish.
    MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
    MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
    var requester:URLRequest=new URLRequest("contactLoader.swf");
    loader2 = null;
    loader2 = new Loader();
    loader2.name ="contact"
    loader2.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
    function ioError(event:IOErrorEvent):void {
    trace(event);
    try {
    loader2.load(requester);
    } catch (error:SecurityError) {
    trace(error);
    addChild(loader2);
    loader2.x = (stage.stageWidth - 658.65) * .5;
    loader2.y = (stage.stageHeight - 551.45) * .5;
    // remove eventlistner and prevents duplication of info.swf
    MovieClip(root).nav.info.removeEventListener(MouseEvent.MOUSE_DOWN, Down1);
    //ABOUT BUTTON
    //adds eventlistner so that info.swf can be loaded
    MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
    function Down3(event:MouseEvent):void {
    //this re-adds the EventListener for portfolio so that end user can view again if they wish.
    MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
    MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
    var requester:URLRequest=new URLRequest("aboutLoader.swf");
    loader3 = null;
    loader3 = new Loader();
    loader3.name ="about"
    loader3.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
    function ioError(event:IOErrorEvent):void {
    trace(event);
    try {
    loader3.load(requester);
    } catch (error:SecurityError) {
    trace(error);
    addChild(loader3);
    loader3.x = (stage.stageWidth - 482) * .5 - 260;
    loader3.y = (stage.stageHeight - 492) * .5 - 140;
    removeChild( getChildByName("carousel") );
    removeChild( getChildByName("carousel1") );
    // remove eventlistner and prevents duplication of info.swf
    MovieClip(root).nav.about.removeEventListener(MouseEvent.MOUSE_DOWN, Down3);
    stop();

    Andrei1,
    Thank you for the helpful advice. I made the changes as you suggested but I am receiving a #1009 error message even though my site is working the way I wan it to work. I would still like to fix the errors so that my site runs and error free. This is the error I am receiving:
    "TypeError: Error #1009: Cannot access a property or method of a null object reference."
    I'm sure this is not the best method to unload loaders and I am guessing this is why I am receiving the following error message.
         loader.unload();
         loader2.unload();
         loader3.unload();
    I also tried creating a function to unload the loader but received the same error message and my portfolio swf was not showing at all.
         function killLoad():void{
         try { loader.close(); loader2.close; loader3.close;} catch (e:*) {}
         loader.unload(); loader2.unload(); loader3.unload();
    I have a question regarding suggestion you made to set Mouse Event to "null". What does this do setting the MouseEvent do exactly?  Also, since I've set the MouseEvent to null do I also have to set the loader to null? e.g.
    ---- Here is my updated code ----
    // variable for external loaders
    var loader:Loader;
    var loader1:Loader;
    var loader2:Loader;
    var loader3:Loader;
    // makes borders resize with browser size
    function resizeHandler(event:Event):void {
    // resizes portfolio page to center
         loader.x = (stage.stageWidth - loader.width) * .5;
         loader.y = (stage.stageHeight - loader.height) * .5;
    // resizes about page to center
         loader3.x = (stage.stageWidth - 482) * .5 - 260;
         loader3.y = (stage.stageHeight - 492) * .5 - 140;
    //adds gallery.swf to stage at begining of moviie
         Down();
    //PORTFOLIO BUTTON
    //adds eventlistner so that gallery.swf can be loaded
         MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
    function Down(event:MouseEvent = null):void {
    // re adds listener for contact.swf and about.swf
         MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
         MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
    //unloads gallery.swf from enter frame if users presses portfolio button in nav
         var requester:URLRequest=new URLRequest("carouselLoader.swf");
         loader = new Loader();
         loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
         function ioError(event:IOErrorEvent):void {
         trace(event);
         try {
         loader.load(requester);
         } catch (error:SecurityError) {
         trace(error);
         this.addChild(loader);
         loader.x = (stage.stageWidth - 739) * .5;
         loader.y = (stage.stageHeight - 500) * .5;
    // sure this is not the best way to do this - but it is unload external swfs
         loader.unload();
         loader2.unload();
         loader3.unload();
    // remove eventlistner and prevents duplication of gallery.swf
         MovieClip(root).nav.portfolio.removeEventListener(MouseEvent.MOUSE_DOWN, Down);
    //INFORMATION BUTTON
         //adds eventlistner so that info.swf can be loaded
         MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
         function Down1(event:MouseEvent = null):void {
         //this re-adds the EventListener for portfolio so that end user can view again if they wish.
         MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
         MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
         var requester:URLRequest=new URLRequest("contactLoader.swf");
         loader2 = null;
         loader2 = new Loader();
         loader2.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);    
         function ioError(event:IOErrorEvent):void {
         trace(event);
         try {
         loader2.load(requester);
    }      catch (error:SecurityError) {
         trace(error);
         addChild(loader2);
         loader2.x = (stage.stageWidth - 658.65) * .5;
         loader2.y = (stage.stageHeight - 551.45) * .5;
    loader.unload();
    loader2.unload();
    loader3.unload();
         // remove eventlistner and prevents duplication of info.swf
         MovieClip(root).nav.info.removeEventListener(MouseEvent.MOUSE_DOWN, Down1);
    //ABOUT BUTTON
         //adds eventlistner so that info.swf can be loaded
         MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
         function Down3(event:MouseEvent = null):void {
         //this re-adds the EventListener for portfolio so that end user can view again if they wish.
         MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
         MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
         var requester:URLRequest=new URLRequest("aboutLoader.swf");
         loader3 = null;
         loader3 = new Loader();
         loader3.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
         function ioError(event:IOErrorEvent):void {
         trace(event);
         try {
         loader3.load(requester);
    }      catch (error:SecurityError) {
         trace(error);
         addChild(loader3);
         loader3.x = (stage.stageWidth - 482) * .5 - 260;
         loader3.y = (stage.stageHeight - 492) * .5 - 140;
         loader.unload();
         loader2.unload();
         loader3.unload();
         // remove eventlistner and prevents duplication of info.swf
         MovieClip(root).nav.about.removeEventListener(MouseEvent.MOUSE_DOWN, Down3);
         stop();

Maybe you are looking for