objects and garbage collection

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sankarasubbu100
    New Member
    • Jun 2008
    • 2

    objects and garbage collection

    class C
    {
    public static void main(String args[])
    {
    C c1 = new C();
    C c2 = m1(c1);
    C c3 = new C();
    c2 = c3; //6
    anothermethod() ;
    }
    static C m1(C ob1)
    {
    ob1 = new C();
    return ob1;
    }
    }

    After line 6, how many objects are eligible for garbage collection?

    Ans: 2

    Please tell me as to what are those two objects here and how?

    Thanks in advance...
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    I'd say only one object can go; the one created by the m1() method and previously
    assigned to variable c2. Why do you think two objects are garbage?

    kind regards,

    Jos

    Comment

    • blazedaces
      Contributor
      • May 2007
      • 284

      #3
      Originally posted by JosAH
      I'd say only one object can go; the one created by the m1() method and previously
      assigned to variable c2. Why do you think two objects are garbage?

      kind regards,

      Jos
      This confuses me as well. Why is c1 not eligible for garbage collection? anotherMethod() must be static, so after the method is completed the program will exit and remove c1 and the pointer to c2 and c3 from memory, no?

      Just so you know I have absolutely no expertise when it comes to garbage collection so I'm asking out of curiosity.

      -blazed

      Edit: And about the previous thread, I always thought java had no pointers and only references, so it always copied the memory to a new location when using object1 = object 2. I was clearly mistaken...

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by blazedaces
        This confuses me as well. Why is c1 not eligible for garbage collection? anotherMethod() must be static, so after the method is completed the program will exit and remove c1 and the pointer to c2 and c3 from memory, no?
        Yep, but the question was how many objects can be garbage collected just after
        the assignment c2= c3, i.e. *before* that other method was called.

        Originally posted by blazedaces
        Edit: And about the previous thread, I always thought java had no pointers and only references, so it always copied the memory to a new location when using object1 = object 2. I was clearly mistaken...
        References and pointers are similar here. Jim Gossling choose to use the noun
        'reference' instead of 'pointer', maybe because Java doesn't have any pointer
        arithmetic as C does.

        Fact remains that the OP is making this all far more complicated than it actually
        is; only the object previously pointed to by c2 can be safely removed.

        kind regards,

        Jos

        Comment

        • blazedaces
          Contributor
          • May 2007
          • 284

          #5
          Originally posted by JosAH
          Yep, but the question was how many objects can be garbage collected just after
          the assignment c2= c3, i.e. *before* that other method was called.



          References and pointers are similar here. Jim Gossling choose to use the noun
          'reference' instead of 'pointer', maybe because Java doesn't have any pointer
          arithmetic as C does.

          Fact remains that the OP is making this all far more complicated than it actually
          is; only the object previously pointed to by c2 can be safely removed.

          kind regards,

          Jos
          Alright, then this all makes a lot of sense.

          And the psuedo-reference pointer also makes sense as an extremely efficient way to have different variables, but still save space.

          So may I ask, if you do the following:

          Code:
          String test1 = new String("testing1");
          String test2 = test1;
          test2 = test2 + test1;
          System.out.println("test1: " + test1);
          System.out.println("test2: " + test2);
          What exactly happens in the lower level code. At line two (String test 2 =test1) test2 point to the same memory location as test1, correct? But then, after line 3, does test2 point to a new location in memory? Does memory get reallocated every time an object is changed?

          Or does the concatenation do something like simply adding character bytes to the end of the sequence of bytes, so previously test2 pointed to character bytes 0-7 (what test1 points to), but afterwards it points to 0-15?

          -blazed

          Comment

          • BigDaddyLH
            Recognized Expert Top Contributor
            • Dec 2007
            • 1216

            #6
            Originally posted by blazedaces
            Code:
            String test1 = new String("testing1");
            String test2 = test1;
            test2 = test2 + test1;
            System.out.println("test1: " + test1);
            System.out.println("test2: " + test2);
            What exactly happens in the lower level code. At line two (String test 2 =test1) test2 point to the same memory location as test1, correct?
            Correct, or rather (since references may not hold something as implementation-dependent as a "memory location") test1 and test2 reference the same object.

            And by the way, it simpler to write:
            [CODE=Java]String test1 = "testing1";[/CODE]

            Originally posted by blazedaces
            But then, after line 3, does test2 point to a new location in memory? Does memory get reallocated every time an object is changed?
            Not in general, you're dealing with the specific case of strings. That assignment is equivalent to this code:

            [CODE=Java]StringBuilder b = new StringBuilder() ;
            b.append(test2) ;
            b.append(test1) ;
            test2 = b.toString();[/CODE]

            Originally posted by blazedaces
            Or does the concatenation do something like simply adding character bytes to the end of the sequence of bytes, so previously test2 pointed to character bytes 0-7 (what test1 points to), but afterwards it points to 0-15?

            -blazed
            That's what is happening in the StringBuilder. The "+" notation is a sort of "syntactic sugar" to make the code look sweeter.

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #7
              Originally posted by blazedaces
              Alright, then this all makes a lot of sense.

              And the psuedo-reference pointer also makes sense as an extremely efficient way to have different variables, but still save space.

              So may I ask, if you do the following:

              Code:
              String test1 = new String("testing1");
              String test2 = test1;
              test2 = test2 + test1;
              System.out.println("test1: " + test1);
              System.out.println("test2: " + test2);
              What exactly happens in the lower level code. At line two (String test 2 =test1) test2 point to the same memory location as test1, correct? But then, after line 3, does test2 point to a new location in memory? Does memory get reallocated every time an object is changed?

              Or does the concatenation do something like simply adding character bytes to the end of the sequence of bytes, so previously test2 pointed to character bytes 0-7 (what test1 points to), but afterwards it points to 0-15?

              -blazed
              The lazy answer is: turn that code snippet into a simple class, compile it using
              javac so that you have a .class file and then use javap, the disassembler and
              see what actually happens. Use javap -c YourClass and see the results.

              Java isn't playing any tricks on you, i.e. if you add two strings using the + operator
              the compiler generates code for the StringBuilder that actually adds those two
              Strings together and produces the result. Have a look at the output of javap and
              see for yourself. btw javap is one of the tools that come with your jdk distribution.

              kind regards,

              Jos

              Comment

              • blazedaces
                Contributor
                • May 2007
                • 284

                #8
                The StringBuilder class! I've always used StringBuffer... Good to know this exists since it seems even more efficient (faster implementation according to the API).

                Well, it's good that I now know better exactly how Java works. I should probably ask in the python section how it works exactly in python, but I assume it's similar.

                -blazed

                Comment

                • blazedaces
                  Contributor
                  • May 2007
                  • 284

                  #9
                  Originally posted by JosAH
                  The lazy answer is: turn that code snippet into a simple class, compile it using
                  javac so that you have a .class file and then use javap, the disassembler and
                  see what actually happens. Use javap -c YourClass and see the results.

                  Java isn't playing any tricks on you, i.e. if you add two strings using the + operator
                  the compiler generates code for the StringBuilder that actually adds those two
                  Strings together and produces the result. Have a look at the output of javap and
                  see for yourself. btw javap is one of the tools that come with your jdk distribution.

                  kind regards,

                  Jos
                  Well, I'm having a little bit of trouble. I've always used JCreator or some kind of IDE to use java and compile files/projects. So for some reason or another besides the "java" none of the other packages are available when I go to the command prompt (in windows, maybe I should switch to linux? My computer is dual boot). So javap and javac produce a response of "'javac' is not recognized as an internal or external command, operable program of batch file".

                  That stinks. I always assumed they were automatically implemented when I installed java. Great. Now to look up how to make them work. Unless you can tell me a way to do it through my IDE. I can add the "compiler" javap as a tool, but I can't figure out a way to use it when I click run instead of using the default other than changing the default compiler...

                  -blazed

                  Comment

                  • BigDaddyLH
                    Recognized Expert Top Contributor
                    • Dec 2007
                    • 1216

                    #10
                    Originally posted by blazedaces
                    Well, I'm having a little bit of trouble. I've always used JCreator or some kind of IDE to use java and compile files/projects. So for some reason or another besides the "java" none of the other packages are available when I go to the command prompt (in windows, maybe I should switch to linux? My computer is dual boot). So javap and javac produce a response of "'javac' is not recognized as an internal or external command, operable program of batch file".

                    That stinks. I always assumed they were automatically implemented when I installed java. Great. Now to look up how to make them work. Unless you can tell me a way to do it through my IDE. I can add the "compiler" javap as a tool, but I can't figure out a way to use it when I click run instead of using the default other than changing the default compiler...

                    -blazed
                    Program java.exe is in the bin of your JRE, while javac.exe and other tools are in the bin folder of your JDK. You need to either type in the absolute path of the program, or edit your PATH environment variable:

                    Comment

                    • blazedaces
                      Contributor
                      • May 2007
                      • 284

                      #11
                      Originally posted by BigDaddyLH
                      Program java.exe is in the bin of your JRE, while javac.exe and other tools are in the bin folder of your JDK. You need to either type in the absolute path of the program, or edit your PATH environment variable:

                      http://java.sun.com/docs/books/tutor...ems/index.html
                      I've edited my path file and can now run both just fine from command prompt. But now after I run javac and make the class file, even though I know the file is there, when I try to run javap -c "classname.clas s" it spits out "ERROR: Could not find TestProgram.cla ss"

                      Any ideas?

                      -blazed

                      Comment

                      • BigDaddyLH
                        Recognized Expert Top Contributor
                        • Dec 2007
                        • 1216

                        #12
                        Like java.exe, javap takes the name of the class, not the filename:

                        Code:
                        javap -c YourClass
                        or

                        Code:
                        javap -c com.acme.widget.YourClass

                        Comment

                        • blazedaces
                          Contributor
                          • May 2007
                          • 284

                          #13
                          Thanks man, and here's the output:
                          Code:
                          Compiled from "TestProgram.java"
                          public class TestProgram extends java.lang.Object{
                          public TestProgram();
                            Code:
                             0:   aload_0
                             1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
                             4:   return
                          
                          public static void main(java.lang.String[]);
                            Code:
                             0:   new     #2; //class java/lang/String
                             3:   dup
                             4:   ldc     #3; //String testing1
                             6:   invokespecial   #4; //Method java/lang/String."<init>":(Ljava/lang/Strin
                          g;)V
                             9:   astore_1
                             10:  aload_1
                             11:  astore_2
                             12:  new     #5; //class java/lang/StringBuilder
                             15:  dup
                             16:  invokespecial   #6; //Method java/lang/StringBuilder."<init>":()V
                             19:  aload_2
                             20:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(Ljava/lang/
                          String;)Ljava/lang/StringBuilder;
                             23:  aload_1
                             24:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(Ljava/lang/
                          String;)Ljava/lang/StringBuilder;
                             27:  invokevirtual   #8; //Method java/lang/StringBuilder.toString:()Ljava/la
                          ng/String;
                             30:  astore_2
                             31:  getstatic       #9; //Field java/lang/System.out:Ljava/io/PrintStream;
                             34:  new     #5; //class java/lang/StringBuilder
                             37:  dup
                             38:  invokespecial   #6; //Method java/lang/StringBuilder."<init>":()V
                             41:  ldc     #10; //String test1:
                             43:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(Ljava/lang/
                          String;)Ljava/lang/StringBuilder;
                             46:  aload_1
                             47:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(Ljava/lang/
                          String;)Ljava/lang/StringBuilder;
                             50:  invokevirtual   #8; //Method java/lang/StringBuilder.toString:()Ljava/la
                          ng/String;
                             53:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/St
                          ring;)V
                             56:  getstatic       #9; //Field java/lang/System.out:Ljava/io/PrintStream;
                             59:  new     #5; //class java/lang/StringBuilder
                             62:  dup
                             63:  invokespecial   #6; //Method java/lang/StringBuilder."<init>":()V
                             66:  ldc     #12; //String test2:
                             68:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(Ljava/lang/
                          String;)Ljava/lang/StringBuilder;
                             71:  aload_2
                             72:  invokevirtual   #7; //Method java/lang/StringBuilder.append:(Ljava/lang/
                          String;)Ljava/lang/StringBuilder;
                             75:  invokevirtual   #8; //Method java/lang/StringBuilder.toString:()Ljava/la
                          ng/String;
                             78:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/St
                          ring;)V
                             81:  return
                          
                          }
                          ...

                          Did I do this just to verify what was said above about what java is actually doing with the "+" operator on strings? Good to know... but this was never an issue of mine.

                          Thank you much for your help and knowledge.

                          -blazed

                          Comment

                          Working...