Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2005

Tip: Looking for answers? Try searching our database.

Garbage collection question?

Thread view: 
Knute Johnson - 11 Nov 2005 22:34 GMT
If I have a method and that method has as a parameter, a new Object()
(no reference variable), will that Object get marked for garbage
collection after the method returns?  Or ever?

    method(new Object()) { ... }

Signature

Knute Johnson
email s/nospam/knute/

Moloch - 11 Nov 2005 23:28 GMT
> If I have a method and that method has as a parameter, a new Object() (no
> reference variable), will that Object get marked for garbage collection
> after the method returns?  Or ever?
>
>     method(new Object()) { ... }

This depends of what you are doing with that parameter in your method...

If you don't do anything with it will be elligible for garbage collection,
if you let for example an instance variable refer to it, it won't.
Monique Y. Mudama - 11 Nov 2005 23:32 GMT
> If I have a method and that method has as a parameter, a new
> Object() (no reference variable), will that Object get marked for
> garbage collection after the method returns?  Or ever?
>
>      method(new Object()) { ... }

I'll take a stab at this.

I believe that it will be eligible for garbage collection after
exiting the method in which your quoted line was called, but only if
it wasn't somehow given a reference inside method().

ie

/**
* Will not be GC'd
*/
void method (JComponent jc)
{
    myJPanel.add(jc);
}   

/**
* Will be GC'd, not after this method completes,
* but after its caller completes (I think, not sure)
*/
void method (JComponent jc)
{
    System.out.println (jc);
}   

Anyone care to correct me?

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

HalcyonWild - 12 Nov 2005 02:12 GMT
> If I have a method and that method has as a parameter, a new Object()
> (no reference variable), will that Object get marked for garbage
[quoted text clipped - 6 lines]
> Knute Johnson
> email s/nospam/knute/

Wanna give this a shot. Run it for a long enough loop. If it finally
throws OutOfMemoryError, or does something strange, the GC aint working
on this.

class Trial
{
    public static int x=0;
    public static void main(String[] args)
    {
        Trial t = new Trial();
        for (; x< 100000; x++)
        {
            t.method("anything");
        }
    }

    public void method
       (
new String("A very long string goes here. copy this string and paste it
back again and again. This string will be quite long then for a simple
test. ")
        )
       {
        System.out.println(x);
    }
}
HalcyonWild - 12 Nov 2005 02:18 GMT
> If I have a method and that method has as a parameter, a new Object()
> (no reference variable), will that Object get marked for garbage
[quoted text clipped - 6 lines]
> Knute Johnson
> email s/nospam/knute/

Also such a construct method( new Object() ) { /*somecode*/ }
gives me a compilation error.
==================================

Trial.java:13: illegal start of type
    public void method(new String("A very long string goes here. copy this
string and paste it back again and again. This string will be quite
long then for a simple test. "))
                          ^
Trial.java:17: <identifier> expected
}
^
2 errors
=================================
John C. Bollinger - 12 Nov 2005 03:16 GMT
> If I have a method and that method has as a parameter, a new Object()
> (no reference variable), will that Object get marked for garbage
> collection after the method returns?  Or ever?
>
>     method(new Object()) { ... }

Perhaps we could help you better if you explained why you are worried
that the object might *not* be eligible.  (If indeed you still are
concerned after the previous two responses.)  In addition to the other
posters' responses, I'll add that it is possible for the object to
become eligible for garbage collection even /before/ the method returns.

I have to admit to a bit of bemusement at the question's suggestion that
/not/ storing a copy of an object's reference could impede collection of
that object.  Storing copies of the reference is precisely what /does/
interfere with collection of that object.

Signature

John Bollinger
jobollin@indiana.edu

Knute Johnson - 12 Nov 2005 18:25 GMT
>> If I have a method and that method has as a parameter, a new Object()
>> (no reference variable), will that Object get marked for garbage
[quoted text clipped - 12 lines]
> that object.  Storing copies of the reference is precisely what /does/
> interfere with collection of that object.

I normally don't even think about garbage collection.  I know it works
and works well.  I'm working on a very large application (for me anyway)
that will have to run continuously for months.  A small leak over a long
period of time could end up a big break in the dam.  So I got to
wondering how it would be possible to write code that would not be able
to be garbage collected.  Since I really don't know how it works, that
was my first question.

So for my second question, you often see code like this:

for (;;) {
    Object o = new Object();
    ....
}

You could potentially create lots of objects.  When you make the first
pass through the loop a new Object is created.  On subsequent passes is
the previous then marked for garbage collection?  Is the reference o
created on the stack too and is it reused?  Do references get garbage
collected?

Thanks,

Signature

Knute Johnson
email s/nospam/knute/

John C. Bollinger - 13 Nov 2005 02:46 GMT
> I normally don't even think about garbage collection.  I know it works
> and works well.  I'm working on a very large application (for me anyway)
[quoted text clipped - 14 lines]
> pass through the loop a new Object is created.  On subsequent passes is
> the previous then marked for garbage collection?

An object automatically becomes eligible for garbage collection when it
ceases to be reachable from any live thread via a chain of strong
(normal) references.  That is the only criterion.  Modern VMs typically
do not monitor assignment statements to make that determination; instead
they periodically trace reference chains to find which objects need to
be /kept/.

In the example you present, the Object created at the top of each loop
iteration becomes eligible for GC as soon as a new reference is assigned
to variable o, *provided that* the old Object's reference has not been
assigned to some object that persists across loop iterations.  (For
example, if the loop added the object to a List then the Object would
not become eligible for GC before the List did.)

>                                                   Is the reference o
> created on the stack too and is it reused?

Local variables occupy space on the stack, but the number of local
variable slots in a stack frame is determined by the compiler.  Almost
certainly, each iteration of the loop will use the same slot to
represent variable o.  Even if different slots were used, the stack
frame size is fixed at compile time, so an infinite loop will quickly
have to start reusing variable slots, so you will not get a memory leak
from this direction.

>              Do references get garbage
> collected?

When a thread returns from a method, its stack frame for that method
invocation is popped, freeing all the memory occupied by the local
variables of that method for that invocation.  This isn't garbage
collection per se, but I think it addresses your concern even better.

Signature

John Bollinger
jobollin@indiana.edu

Chris Smith - 13 Nov 2005 06:12 GMT
> An object automatically becomes eligible for garbage collection when it
> ceases to be reachable from any live thread via a chain of strong
> (normal) references.  That is the only criterion.

Since we seem to be in the mood to talk about garbage collection a lot,
here is the full story.

Garbage collection theorists (at least, those who are picky about words)
distinguish between these concepts:

   An object is LIVE if the program will access it at some point in the
   future.  An ideal garbage collector would collect all objects that
   are not live.  However, such a garbage collector is impossible in
   the general case.  It would need to know all future actions of the
   user in advance, for example.  Some kind of ESP would be needed.

   An object is ACTIVE is some possible future execution of the current
   application could potentially access it.  Active objects form a
   superset of live objects.  This category has the advantage that,
   unlike liveness, it can be determined without any ability to predict
   the future.

   An object is REACHABLE if there is any path to reach it through
   variables that are lexically in scope (regardless of accessibility)
   from the root set.  This is a superset of active objects.  It has
   the advantage that it is much easier to determine than activeness.

Garbage collectors fall into several kinds:

Collectors that cannot collect even all unreachable objects are known as
"conservative", whereas garbage collectors that collect all unreachable
objects are "precise".

Garbage collectors that even collect some reachable but inactive objects
aren't given an adjective, but are said to be doing "liveness analysis".  
The word is applied regardless of whether all inactive objects are
collected, or just some.  This is an odd term when you consider that
what's really happening is more like activeness analysis, but
nevertheless the word stuck.  Modern garbage collection work is less
concerned with preserving the meaning of the word "live", since strict
liveness is a completely useless concept.  Liveness analysis is still
immensely difficult in the general case; global liveness analysis is
practically never done.  Local liveness analysis, though, is somewhat
common.

Garbage collectors that collect some active objects are called "broken",
and are generally called that in an angry voice.

As for Java, Dale King and I have often argued about whether the Java
specification allows Java to collect only unreachable objects, or also
inactive objects as well.  I believe the latter to be the case; in fact,
I think the spec is crystal clear on the matter; but Dale disagrees.  
Search Google groups for more on this one, if you're interested.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Roedy Green - 13 Nov 2005 06:25 GMT
>   An object is ACTIVE is some possible future execution of the current
>    application could potentially access it.  Active objects form a
[quoted text clipped - 6 lines]
>    from the root set.  This is a superset of active objects.  It has
>    the advantage that it is much easier to determine than activeness.

Could you give an example of an object that is reachable but not
active?
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Benji - 13 Nov 2005 06:34 GMT
> Could you give an example of an object that is reachable but not
> active?

This is not generally possible to calculate, but...active means that it
*will* be used again.  You can have a reachable object that will not be
used again in your program.  But there aren't very many cases in which
you can determine this.

One example of an easily determinable not-live object that is reachable is
a local variable that is not used after the current location in the code.

public void foo()
{
 Object o = new Object();
 //lots of code where o is used

 //o is not live here, but it is reachable.

 //lots of code where o is not used
}

Signature

Of making better designs there is no end,
 and much refactoring wearies the body.

Chris Smith - 13 Nov 2005 17:24 GMT
> Could you give an example of an object that is reachable but not
> active?

Sure:

class A
{
   public String f = new String("test");
   public String g = "test2";

   public static void main(String[] args)
   {
       A a = new A();

       System.out.println(a.f);
       System.out.println(a.g); // ***
   }
}

During the execution of the starred line, the String referred to by a.f
is reachable, but not active.  The reference a is a local variable in an
active stack frame, so it belongs to the root set, and it's possible to
reach that String from a.  However, no possible continuing computation
of the program at that point could cause the String to be accessed.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Roedy Green - 13 Nov 2005 18:12 GMT
>> Could you give an example of an object that is reachable but not
>> active?
>
>Sure:

thank you. I have summarised this discussion at
http://mindprod.com/jgloss/garbagecollection.html#TERMINOLOGY
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Chris Uppal - 13 Nov 2005 11:48 GMT
> Active objects form a superset of live objects.
[...]
> [the set of reachable objects] is a superset of active objects.

Do you happen to know of any studies of how good the two approximations are in
practise ?  It would be easy to determine (for a particular program run) how
well "reachableness" was tracking "activeness" was tracking "liveness" by
recording a trace of memory activity (and analysing it later), and I know that
many studies used such traces.  I can't, though, remember ever seeing an
explicit comparison of the growth patterns of the three sets.

   -- chris
Knute Johnson - 14 Nov 2005 02:45 GMT
>> I normally don't even think about garbage collection.  I know it works
>> and works well.  I'm working on a very large application (for me
[quoted text clipped - 46 lines]
> variables of that method for that invocation.  This isn't garbage
> collection per se, but I think it addresses your concern even better.

Thanks John and everybody else that answered.  I appreciate the time and
effort for my enlightenment.

Signature

Knute Johnson
email s/nospam/knute/

Roedy Green - 13 Nov 2005 02:50 GMT
On Sat, 12 Nov 2005 10:25:00 -0800, Knute Johnson
<nospam@ljr-2.frazmtn.com> wrote, quoted or indirectly quoted someone
who said :

>for (;;) {
>     Object o = new Object();
[quoted text clipped - 4 lines]
>pass through the loop a new Object is created.  On subsequent passes is
>the previous then marked for garbage collection?

There is no such thing as "marking for garbage collection".  Objects
are orphaned when nothing is pointing to them.  Every once is a while
live objects are collected and everything else gets left behind. There
is no individual burial of dead objects.

The variable o points to a new Object each time through the loop. This
means, unless you did something else with the previous object, since o
no longer points to it, nothing does. Its a goner.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 13 Nov 2005 02:53 GMT
On Sat, 12 Nov 2005 10:25:00 -0800, Knute Johnson
<nospam@ljr-2.frazmtn.com> wrote, quoted or indirectly quoted someone
who said :

>Is the reference o
>created on the stack too and is it reused?  Do references get garbage
>collected?

The reference slot for a local variable lives on the stack at a fixed
location for the life of the method. There is only one slot per
variable even for a variable defined in a loop.. When the method ends,
the stack is popped and all its references and parameters disappear.
What they were pointing to become eligible for garbage collection,
unless something else points to them.

In special cases two variables can share the same slot, but
conceptually you can think of each local variable having its own slot.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 13 Nov 2005 02:56 GMT
On Sat, 12 Nov 2005 10:25:00 -0800, Knute Johnson
<nospam@ljr-2.frazmtn.com> wrote, quoted or indirectly quoted someone
who said :

>Do references get garbage
>collected?

No, only objects. for a rather wigged out metaphor to explain the
differences between references and objects see
http://mindprod.com/jgloss/reference.html

For those who think this is simple. Read the metaphor.  It is very
complicated because references and objects are very complicated.

It is just easy because you long ago figured it out, not because it is
inherently simple.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 12 Nov 2005 03:42 GMT
On Fri, 11 Nov 2005 14:34:59 -0800, Knute Johnson
<nospam@ljr-2.frazmtn.com> wrote, quoted or indirectly quoted someone
who said :

>If I have a method and that method has as a parameter, a new Object()
>(no reference variable), will that Object get marked for garbage
>collection after the method returns?  Or ever?
>
>     method(new Object()) { ... }

Objects don't get marked for GC, they get marked to be kept by being
referenced.

So there is a reference to new object pushed to the stack. The callee
might copy it somewhere, but if it does not, when the callee returns
that value will be popped off the stack. The object will then be free
floating and a candidate for GC.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

HalcyonWild - 12 Nov 2005 15:13 GMT
> On Fri, 11 Nov 2005 14:34:59 -0800, Knute Johnson
> <nospam@ljr-2.frazmtn.com> wrote, quoted or indirectly quoted someone
[quoted text clipped - 13 lines]
> that value will be popped off the stack. The object will then be free
> floating and a candidate for GC.

But it does not even compile, forget about being collected by GC.
Knute Johnson - 12 Nov 2005 18:06 GMT
> But it does not even compile, forget about being collected by GC.

public class test {
    static void method(Object o) { ; }

    public static void main(String[] args) {
        method(new Object());
    }
}

Signature

Knute Johnson
email s/nospam/knute/

HalcyonWild - 14 Nov 2005 11:41 GMT
> > But it does not even compile, forget about being collected by GC.
>
[quoted text clipped - 5 lines]
>      }
> }

Knute, you earlier said this in your original post. -----
If I have a method and that method has as a parameter, a new Object()
(no reference variable), will that Object get marked for garbage
collection after the method returns?  Or ever?

    method(new Object()) { ... }

-------[end of yoru original post]

Now, where is the semicolon here. There is a difference in your
original post and this post above. Here you are calling the method, and
in your original post you were defining the method.
Well, you got me confused. Anyway, in this case, I dont know if new
Object in the method call, would be GCed after the caller exits, or the
called exits.
Knute Johnson - 14 Nov 2005 17:45 GMT
>>>But it does not even compile, forget about being collected by GC.
>>
[quoted text clipped - 21 lines]
> Object in the method call, would be GCed after the caller exits, or the
> called exits.

The ... means some statements.  It is pseudo code, not complete but only
there for example.  To make the example compilable it needed a
statement.  ; is the shortest statement possible.

Signature

Knute Johnson
email s/nospam/knute/

Roedy Green - 14 Nov 2005 20:12 GMT
On Mon, 14 Nov 2005 09:45:47 -0800, Knute Johnson
<nospam@ljr-2.frazmtn.com> wrote, quoted or indirectly quoted someone
who said :

>The ... means some statements.

the problem with that notation now  is that sometimes it is
meaningful, for the array constructor shortcut.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Knute Johnson - 15 Nov 2005 01:38 GMT
> On Mon, 14 Nov 2005 09:45:47 -0800, Knute Johnson
> <nospam@ljr-2.frazmtn.com> wrote, quoted or indirectly quoted someone
[quoted text clipped - 4 lines]
> the problem with that notation now  is that sometimes it is
> meaningful, for the array constructor shortcut.

I guess "// some statement" would have been better but - hindsight :-).

Signature

Knute Johnson
email s/nospam/knute/

Roedy Green - 15 Nov 2005 06:38 GMT
On Mon, 14 Nov 2005 17:38:10 -0800, Knute Johnson
<nospam@ljr-2.frazmtn.com> wrote, quoted or indirectly quoted someone
who said :

>> the problem with that notation now  is that sometimes it is
>> meaningful, for the array constructor shortcut.
>
>I guess "// some statement" would have been better but - hindsight :-).

I have been converting examples to either /* ... */ or // ...
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Knute Johnson - 15 Nov 2005 20:26 GMT
> On Mon, 14 Nov 2005 17:38:10 -0800, Knute Johnson
> <nospam@ljr-2.frazmtn.com> wrote, quoted or indirectly quoted someone
[quoted text clipped - 6 lines]
>
> I have been converting examples to either /* ... */ or // ...

I'll try to remember that :-).

Signature

Knute Johnson
email s/nospam/knute/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.