Nested object reference after garbage collection

I have a question about how GC works.
Assume I have a Class A which has a reference to class B inside it. I create a object of class B and assign to member variable of class A.
Now when obja is no longer needed, I set it null. And when GC runs, the object will be removed from memory. But should I also need to explicitly set objb to null. If i don't set it, will it also get garbage collected when obja is being removed from memory?
public class ClassA {
private ClassB objB = new ClassB();
private static void main(String args[]) {
ClassA obja = new ClassA();
obja = null;
}

801625 wrote:
But should I also need to explicitly set objb to null.No.
If i don't set it, will it also get garbage collected when obja is being removed from memory?If there are no other references outside of classA to the object referenced by objB (in your case an instance of ClassB) then it will be garbage collected.
Note - the only time one needs to set a reference to null is if one wants the object it references to be eligible for GC before the reference goes out of scope. There is a slight complication to this - depending on the JVM implementation, if a reference is defined in a block internal to a method then even though it goes out of scope when execution goes out of the block anything it references may not be eligible for GC until the method exits.

Similar Messages

  • 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.

  • Is this object available for garbage collection

    public class MyClass {
    public static void main(String args []){
    new MyClass().myFunc();
    //Because I don't assign this reference to a variable, is it available for collection at this point?
    public void myFunc(){  }
    Thanks ..... Jimmy

    What do you mean "in most cases"? I assume you don't
    mean that most methods in any java program should be
    static, Of course not... please actually read the context of my post. "in most cases" where the code is similar to what the OP posted, a static method would probably be appropriate. In code where you are creating a new instance of a class for the sole purpose of calling a method and not retaining a reference to it, it should probably be a static method. Look at the OP's code:
    public class MyClass {
      public static void main(String args []){
        new MyClass().myFunc();
      public void myFunc(){
    }Notice that the OP does not keep a reference to the object, simply calling a method and leaving it at that. I am saying that in this situation, it would probably be more appropriate to do the following:
    public class MyClass {
      public static void main(String args []){
        MyClass().myFunc();
      public static void myFunc(){
    }I imagine that there are situations where the OP's original design may be useful, but in most situations, a static method is appropriate.
    This isn't that complicated... I see no need to get into an argument over it. Please don't just attempt to make me look like a fool (I do a fine job of that on my own).

  • Find out references to objects (garbage collection)

    Is there an easy way to find out, which references prevent the garbage collector from collecting my old objects, which I expect should be collected? Something like System.out.println(...)

    if you just want an object to be garbage collected, just
    make sure you de-reference is completely.CMueller obviously doesn't know which references prevent garbage collection so naturally he cannot set those references to null, now can he?
    o = null; // sets the value to null and drops all the referencesThat is simply not true. Removing a reference to an object doesn't affect any other references to that object.
      Object o1,o2;
      //create an object and make o1 reference it
      o1=new Object();
      //make o2 reference the same object as o1 references
      o2=o1;
      //now there are two references to the object
      //make o1 reference null
      o1=null;
      //at this point there is still one reference (o2) to
      //the object and therefore the object is NOT garbage
      //which means that it can NOT be collected by the GC- Marcus Sundman

  • Local ref garbage collection within "nested" JNI calls

    I am using a JVM started in C++ to make calls to java classes. The C++ code makes JNI call into the JVM which instantiates a java class. The java class, in the course of execution, makes other JNI calls. All this happens on one thread of execution.
    What I am seeing is that local references from the native methods being called by the java class are not being released until the initial C++ native call exits. The JNI spec (text included below) seems to indicate there is registry of "nonmovable local references to Java objects" which "keeps the objects from being garbage collected". Is there only one such registry which does not get deleted until the initial C++ native call exits? If so, this would explain what I am seeing. How do I get around it?
    Thanks,
    Iztok
    From the JNI spec:
    "To implement local references, the Java VM creates a registry for each
    transition of control from Java to a native method. A registry maps nonmovable local references to Java objects, and keeps the objects from being garbage collected. All Java objects passed to the native method (including those that are returned as the results of JNI function calls) are automatically added to the registry. The registry is deleted after the native method returns, allowing all of its entries to be garbage collected."

    When I say "initial" I mean the initial C++ JNI call into a JVM running in a C++ process as shown in the pseudo code below. initNativeFunc() makes a call to Foo.doSomething() function which calls nativeFunc2 (another native function). Only a local reference to Retval was created in nativeFunct2, so when nativeFunct2 returns and the Retval is no longer used in Foo it should be a candidate for garbage collection. But this is not what happens. The Retval from nativeFunc2 is not being cleaned up until Foo.doSomething() returns. If I make the loop in Foo.doSomething() long enough, NewDoubleArray() returns a NULL when it runs out of memory.
    void initNativeFunc() {
    jclass clazz = env->FindClass("Foo");
    jmethodID mid = env->GetMethodID(clazz, "doSomething", "()V");
    env->CallVoidMethod(clazz, mid, ...);
    JNIEXPORT jobject JNICALL nativeFunc2() {
    jclass clazz = env->FindClass("Retval");
    jmethodID mid = env->GetMethodID("Retval, "<init>", "()V");
    jobject retval= env->NewObject(clazz, mid);
    jdoubleArray da = env->NewDoubleArray(100000);
    jfieldID fid = ...
    env->SetObjectField(retval, fid, da);
    return retval;
    public class Foo {
    public native void nativeFunc2();
    public void doSomething() {
    for (int i = 0; i < 100; i++) {
    Retval retval = nativeFunc2();
    }

  • 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?

  • How strong ,soft ,weak ,phantom references are used in garbage collection

    Hi
    to all here.I have doubt that how garbage collection is deciding to cleaning up heap , and what are the roles of strong , soft , weak and phantom reference in garbage collection, i went throgh sun's java docs but i couldn't get any clear idea about those , please can anyone explain me with nice examples for which i will be really thankful.

    See:
    http://java.sun.com/developer/technicalArticles/ALT/RefObj/

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Garbage Collection in Java

    Hi,
    In the case of Garbage Collection (GM), if I created a object s in line1, done operation in line2 and made s as null in line3 and after some more execution (may be 10000 lines of code or may running of the prog. for 2 days), I will use same var. s again. Will it will able to work or already Garabage Collected ? Can, I get proper answer ?
    bye
    RaviGanesh

    the object referred to by reference "s" becomes a candidate for garbage collection as soon as the last reference to it is broken. so when you make the reference "s" refer to null, if no other references refer to the originat object, the object can be garbage collected. you are free to assign the reference to other objects at any time (supposing you haven't declared the reference final).
    note how careful i was to distinguish "object" from "reference" here. in java, when we say:  Object o = new Object();o is the reference, the new Object is the object. if i then say:  Object p = o;there are now two references to the initially created object, o and p.
    keep in mind the distinction between objects and references to them, and you should be on your way.

  • Garbage Collection Help

    My understanding of garbage collection is that resources utilized by an object are released when no reference to the object exist. I accomplish this by ensuring that all references to an unneeded object are null.
    My question/concern is this. If I have an object "A" that has references to other objects "B", "C", and "D", will the all objects be elibible for garbage collection when the reference to object A is set to null? I suspect that objects "B", "C", and "D" persist until the virtual machine is terminated.
    Is the practice of creating a method within a class to make all inner objects eligible for garbage collection prior to setting the object reference to null. (i.e. set objects "B", "C", and "D" to null prior to setting "A" to null).
    Maybe I am just paranoid??

    My understanding of garbage collection is that
    resources utilized by an object are released when no
    reference to the object existThat's not correct. Objects can have references that point to them and still be garbage collected. For example:
    Vector v = new Vector();
    v.add(new Object());
    v = null;
    After this code is executed, the Vector object has a reference to the "new Object()" created. However, the Vector itself is not reachable, and therefore the "new Object()" is unreachable, and therefore both are collected.
    The garbage collector collects unreachable objects.
    I accomplish this by
    ensuring that all references to an unneeded object are
    null.It is quite rare that setting a reference to null is needed to make an object unreachable. Don't do it -- it makes your code slower, less readable, and harder to modify.
    My question/concern is this. If I have an object "A"
    that has references to other objects "B", "C", and
    "D", will the all objects be elibible for garbage
    collection when the reference to object A is set to
    null? I suspect that objects "B", "C", and "D"
    persist until the virtual machine is terminated.Yes -- all will be collected when A becomes unreachable. As noted earlier, you shouldn't need to set any reference to null for this to happen.
    Is the practice of creating a method within a class to
    make all inner objects eligible for garbage collection
    prior to setting the object reference to null. (i.e.
    set objects "B", "C", and "D" to null prior to setting
    "A" to null).
    Maybe I am just paranoid??Yes. Just let the garbage collector do its job and collect unreachable objects. You should almost never need to write any code to "help" the garbage collector.

  • URL class is not being garbage collected

    I have created two instances of the URL class to specify a file location for each image. I use com.symantec.itools.javax.swing.icons.ImageIcon class to display images specified by each URL instance as icons inside a button. The setImageLocation method(URL location) of the ImageIcon class sets the location to be displayed by this icon. The following is the code snippets used to create the ImageIcon instances:
    private URL greenIconURL;
    private URL redIconURL;
    com.symantec.itools.javax.swing.icons.ImageIcon green_icon = new com.symantec.itools.javax.swing.icons.ImageIcon();
    com.symantec.itools.javax.swing.icons.ImageIcon red_icon = new com.symantec.itools.javax.swing.icons.ImageIcon();
    try
    greenIconURL = new java.net.URL
    ("file:./images/greenline.gif");
    green_icon.setImageLocation(greenIconURL);
    catch (java.net.MalformedURLException error) { }
    try
    redIconURL = new java.net.URL
    ("file:./images/redline.gif");
    red_icon.setImageLocation(redIconURL);
    catch (java.net.MalformedURLException error) { }
    I am using JProbe 5.0.1 Memory to determine the loitering objects when I remove the button from the JInternalFrame. I am using Java 1.2.2_08 version. The JProbe Memory Leak Doctor indicates that each URL instance has a reference to an entry in a HashMap table. The reference graph from the root set has a reference to SoftCache to HashMap to HashMap$Entry. To make this URL instance eligible for garbage collection, JProbe Memory Leak Doctor indicates I must remove the entry from the HashMap. How do I get access to this HashMap to remove the entry? If this is a problem with the version of the JDK, please let me know. Thank you in advance for your assistance.

    <root>Statics
    -->sun.misc.SoftCache->java.util.HashMap->java.util.Has
    Map$Entry[]->java.util.HashMap$Entry->java.net.URL
    I do not an instance of HashMap in my class.
    Therefore, the HashMap is either created by URLclass
    or the
    com.symantec.itools.javax.swing.icons.ImageIcon
    class.SoftCache seems to have a normal HashMap inside
    it/* Hash table mapping keys to ValueCells */
    private Map hash;but if that is the HashMap in JProbe
    information then the URL would have to be a key in
    the map - otherwise there'd be another object in the
    chain of class SoftCache.ValueCell
    are you certain that the java.net.URL's in that
    hashmap are your ones?
    out of curiosity - are you certain that the URL's are
    the/a problem (are you getting an OutOfMemoryError?)
    asjfThe button that contains the URL's is the only one on the JInternalFrame. The JProbe Memory Debugger displays the java.net package name, the URL class name, the count (2), and the Count Change (+2). When I remove the button from the JInternalFrame, the aforementioned numbers on the Instance Summary remain the same. The snapshot of the Java Heap reveals that the two instances of the URL class are still there. The Memory Leak Doctor shows the reference graph from the root set:
    <root>Statics->SoftCache->HashMap->HashMap$Entry[]->HashMap$Entry->URL
    When I right click on the arrow between HashMap$Entry[] and HashMap$Entry to remove the reference, I receive the message: "Congratulations this object can be garbage collected..." It appears like private instance of Map in SoftCache is holding a strong reference.
    I am not getting an OutOfMemoryError exception.

  • Garbage collection Java Virtual Machine : Hewlett-Packard Hotspot release 1.3.1.01

    "Hi,
    I try and understand the mechanism of garbage collection of the Java Virtual Machine : Hewlett-Packard Hotspot release 1.3.1.01.
    There is description of this mechanism in the pdf file : "memory management and garbage collection" available at the paragraph "Java performance tuning tutorial" at the page :
    http://h21007.www2.hp.com/dspp/tech/tech_TechDocumentDetailPage_IDX/1,1701,1607,00.html
    Regarding my question :
    Below is an extract of the log file of garbage collections. This extract has 2 consecutive garbage collections.
    (each begins with "<GC:").
    <GC: 1 387875.630047 554 1258496 1 161087488 0 161087488 20119552 0 20119552
    334758064 238778016 335544320
    46294096 46294096 46399488 5.319209 >
    <GC: 5 387926.615209 555 1258496 1 161087488 0 161087488 0 0 20119552
    240036512 242217264 335544320
    46317184 46317184 46399488 5.206192 >
    There are 2 "full garbage collections", one of reason "1" and one of reason "5".
    For the first one "Old generation After " =238778016
    For the second "Old generation After " =238778016
    Thus, "Old generation Before garbage collection" of the second is higher than "Old generation After garbage collection". Why?
    I expected all objects to be allocated in the "Eden" space. And therefore I did not expect to s

    I agree but my current Hp support is not very good on JVM issues.
    Rob Woollen <[email protected]> wrote:
    You'd probably be better off asking this question to HP.
    -- Rob
    Martial wrote:
    The object of this mail is the Hewlett-Packard 1.3.1.01 Hotspot JavaVirtual Machine
    release and its garbage collection mechanism.
    I am interested in the "-Xverbosegc" option for garbage collectionmonitoring.
    I have been through the online document :
    http://www.hp.com/products1/unix/java/infolibrary/prog_guide/java1_3/hotspot.html#-Xverbosegc
    I would like to find out more about the garbage collection mechanismand need
    further information to understand the result of the log file generatedwith the
    "-Xverbosegc"
    For example here is an extract of a garbage collection log file generatedwith
    Hewlett-Packard Hotspot Java Virtual Machine. Release 1.3.1.01.
    These are 2 consecutive rows of the files :
    <GC: 5 385565.750251 543 48 1 161087488 0 161087488 0 0 20119552 264184480255179792
    335544320 46118384 46118384 46137344 5.514721 >
    <GC: 1 385876.530728 544 1258496 1 161087488 0 161087488 20119552 020119552 334969696
    255530640 335544320 46121664 46106304 46137344 6.768760 >
    We have 2 full garbage collections, one of Reason 5 and the next oneof Reason
    1.
    What happened between these 2 garbage collections as we got : "Oldgeneration
    After" of row 2 is higher than "Old generation Before" of row 1? Iexpected Objects
    to be initially allocated in eden and so we could not get "old generation2modified
    between the end of one garbage collection and before the next one.
    Could you please clarify this issue and/or give more information aboutgarbage
    collection mechanisms with the Hewlett-Packard Hotspot Java VirtualMachine. Release
    1.3.1.01.

  • Memory leak in java / forcing garbage collection for unused resource?

    Is there any possibility in big programs if not designed properly for leakage of memory?
    If say i forget to force garbage collection of unused resouces what will happen?
    Even if i am forcing garbage collection how much assurity can be given to do so?
    I need answers w.r.t typical programming examples if someone can provide i will be happy.
    Or any useful link.
    Thanks
    Vijendra

    Memory leaks are usually much related with C/C++ programming since in that language you have direct access to memory using pointers.
    Now, in Java you do not have access to pointers, however you could still tie up your objects in a way that the garbage collection can not remove them.
    Basically, the grabage collection will search all the object implementation, and see if they are referenced or not. If not it will free that memory. However if you, somehow in you code allow a reference to your object then the garbage collection will not displose of that object.
    An example I can think of is when developing web applications. For example storing objects in the session will mean that you will have a reference to the object from the session, therefore the garbage collection will not free up the meomry taken by those objects untill the session has expired.
    That is how I know it... at least that is how they tought it to me!
    regards,
    sim085

  • Swing Transferhandler prevents garbage collection of one Component

    While searching for memory leaks in my app I found out that an object wasn't garbage collected because of a static reference from javax.swing.TransferHandler.
    Once an app has called TransferHandler.exportAsDrag, TransferHandler keeps alive one static reference to a SwingDragGestureRecognizer.
        public void exportAsDrag(JComponent comp, InputEvent e, int action) {
            int srcActions = getSourceActions(comp);
            // only mouse events supported for drag operations
         if (!(e instanceof MouseEvent)
                    // only support known actions
                    || !(action == COPY || action == MOVE || action == LINK)
                    // only support valid source actions
                    || (srcActions & action) == 0) {
                action = NONE;
            if (action != NONE && !GraphicsEnvironment.isHeadless()) {
             if (recognizer == null) {
              recognizer = new SwingDragGestureRecognizer(new DragHandler());
                recognizer.gestured(comp, (MouseEvent)e, srcActions, action);
         } else {
                exportDone(comp, null, NONE);
    ....As you can see there is a call to recognizer.gestured(comp, (MouseEvent)e, srcActions, action). This object saves a reference to the component comp.
    This means that the last Component for which the exportAsDrag method was called (and the gestured call was reached); and all objects refererred to by the Component can not be garbage collected.
    I think in a normal application this will be not much of a problem because it's only a reference to a single Component; but still I think this is not very nice.
    Should I report this as a bug somewhere?

    Something similar seems to happens to JInternalFrame.lastFocusOwner
    Oh well, I guess I shouldn't worry too much about single references; I don't think they immediately cause memory leaks..

  • Garbage collection

    String string1 = "Test"; 
    String string2 = "Today"; 
    string1 = null; 
    string1 = string2; i want know how many objects have been garbage collected by the JVM in this code .
    is there any function of JVM which can tell me how many have been garbage collected for this code.
    here its a small code. the reason i am asking , for large code it would difficult to track manually for garbages. . so is there any way out ?

    for large code it would difficult to track manually
    for garbages. . so is there any way out ?There is an easy way out: stop worrying about it.
    You don't need to "track" garbage. That's the beauty of garbage collection. It's mostly automatic (as long as you don't do anything silly in your code, such as build a huge data structure, and keep it stored in a global variable forever even though the program will never use the data again.)
    Are you a C++ programmer by any chance? I find that sometimes C++ programmers who run into a garbage collecting system tend to obsess about it needlessly, because so much time and attention has to be spent twiddling with memory allocation in C++.
    How many objects does System.gc() collect? Maybe none. Maybe one. Maybe more. System.gc() might not collect anything at all; it might schedule garbage collection to happen at a later time. There are asynchronous garbage collectors that run in their own threads, collecting whenever the cpu has a few spare cycles. Asking "how many objects are collected at point X in the code" makes no sense on those systems.

Maybe you are looking for