Garbage collection question?

K

Knute Johnson

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()) { ... }
 
G

Guest

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

Monique Y. Mudama

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

HalcyonWild

Knute 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()) { ... }



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);
}
}
 
H

HalcyonWild

Knute 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()) { ... }


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
=================================
 
J

John C. Bollinger

Knute 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()) { ... }

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

Roedy Green

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

HalcyonWild

Roedy said:
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.


But it does not even compile, forget about being collected by GC.
 
K

Knute Johnson

HalcyonWild said:
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());
}
}
 
K

Knute Johnson

John said:
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.

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,
 
J

John C. Bollinger

Knute said:
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?

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

Roedy Green

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?

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

Roedy Green

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

Roedy Green

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

Chris Smith

John C. Bollinger said:
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.

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

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
R

Roedy Green

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.

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

Benji

Roedy said:
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
}
 
C

Chris Uppal

Chris said:
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
 
C

Chris Smith

Roedy said:
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.

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

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top