bilbo said:
either.
Is this behavior actually required by a standard-conforming Java
compiler or JVM, or is it just the way that the Sun JDK works? I know
It is a true statement about the characteristics of the bytecode
language, which is independant of the Java language or any particular
implementation of Java tools.
the asssembler output I've inspected from some C and C++ compilers does
indeed decrement and increment the stack pointer when entering and
leaving blocks, so block-scope variables really are implemented as
block-scope.
That is both implementation-specific and irrelevant.
So I don't see why in principle a Java compiler couldn't
couldn't do the same, unless the JVM doesn't support this, or the JLS
forbids it.
The JLS has nothing to say about it, as it is concerned with Java, not
bytecode. A JVM could perhaps support such a thing as an extension, but
classes that made use of such an extension would not be Java-compliant.
For that you might as well just compile to native code -- you would
already have given up most of the advantages of running in a VM anyway.
Even if the the JVM somehow doesn't support block-scope variables, a
reasonable compiler could still generate extra code to set block-scope
variables to null when the block exits, so that the object the
block-scope variable referred to would be able to be GCed before the
function exits.
I don't accept that as a valid criterion for a compiler being
"reasonable". Some would even argue (and have) that a compiler that did
as you say would not be Java compliant. I would not personally go so
far; I think such a compiler could be compliant, but I don't see the
point of demanding one. You can expect a modern JIT-enabled JVM to
compile the corresponding bytecode to native code at runtime if there is
any significant advantage to doing so (and maybe even if there isn't),
and to apply a fairly good suite of optimizations in the process. Such
optimizations can include detecting when the current values of reference
variables are no longer accessed along any potential forward code path,
and taking appropriate action to avoid unnecessarily long-lived objects.
Note that that is a more general optimization than automatically
nullifying reference variables when they go out of (Java) scope.
[...]
bit of code as well. It just seems wrong to have to do this kind of
manual memory management in a GCed language, when the compiler easily
has enough info to do the work for me.
You don't have to do it. In most cases it won't make a difference
anyway. In those cases where it might make a difference, the JIT has a
chance to take care of you. If you actually experience difficulties
with object packratting then a good profiler will help you figure out
those places, if any, where explicitly nullifying reference variables
may help.
John Bollinger
(e-mail address removed)