More stack and heap, 2

Posted on 2000-02-15
Last Modified: 2013-11-23
In the start() method, I have:

                  Label myLabel = new Label("Hello");

Each time you resize the browser, the new instance of Label is added to the Applet container by FlowLayout manager. My question is this. Where is each instance of the Label, the myLabel, stored? It must be on the heap, since each instance is an object. Where, then, is the pointer reference to each instance that is stored on the heap? According to my Sun training, in this situation the instance name myLabel goes on the stack with a pointer reference to the instance on the heap. So the stack fills up with duplicate "myLabel" names, each of which points to a separate instance on the heap.
Question by:HanRui

Expert Comment

ID: 2525441
Is has to do how add works. And I am sure add resizes its internal table to store this extra label. This is done through the stack.

And as you know, Java uses garbage collection, so myLabel will first be allocated from the heap, and after start ends, this memory will be freed.

Author Comment

ID: 2525479
I'm not sure about that. I think the memory on the heap is freed only after the Applet is exited by the browser and disposed. The Label objects that are created and live on the heap stay there after start() completes each cycle of a flow of control, even when it is invoked repeatedly. According to the tech manual, the object lives on independent of the method that created it. That is not so for primitives, which live only on the stack, but I think it works that way for objects on the heap.

Expert Comment

ID: 2525949
>>>Where is each instance of the Label, the myLabel, stored? It must be on the heap, since each instance is an object.

I think so too

>>>Where, then, is the pointer reference to each instance that is stored on the heap?According to my Sun training, in this situation the instance name myLabel goes on the stack with a pointer reference to the instance on the heap.

check out this site which says

Label myLabel; //---> one heap
Label myLabel=new Label(); //new Label() on another heap

please keepin mind that the expensive compaction of objects, which happens as a last resort during the reclaiming of unused memory when object allocation is falling shot of reuquired memory, is nearly eliminated except in the most drastic of circumstances in modern JVM's especially the Hotspot.

Copying & pasting from there

let’s take a look at how the Java runtime system handles these problems.

First, the JVM uses two separate heaps for dynamic and static memory allocation. All class definitions, the Constant Pool, and
method tables are kept in a nongarbage collected heap. So, once a class definition has been read in, the structural information
and methods stay in memory. This does add a little storage overhead but improves performance for classes that come and go
relatively frequently within an application.

The second heap is split into two areas that grow in opposite directions. One area is used to hold object instances, and the
other contains “handles” to those instances. The runtime image of fields and variables in your Java application that reference
object instances do not actually contain pointers to those objects. They contain pointers to a special, fixed-size, heap-based
memory object called a handle. The handle is a structure that contains two pointers, one to the object’s method table and the
other to the actual object instance. The advantage to this layout is that the handles never move in memory, so there is never a
need to keep track of which variables point to which objects when updating pointers after compacting. You simply update the
pointer value of the handle structure.

The object space of the heap is managed in a traditional fashion in that there is a free list and an allocated object list. As objects
are instantiated, the free list is searched for the “first-fit block.” Also, if possible, coalescing happens during this phase (as
opposed to when an instance is put back on the free list) in order to make the garbage collection process faster. In addition, the
dangling reference problem is eliminated by Java, as you are not responsible for explicit object deallocations. The Java language
has a new operator but no corresponding delete.

The garbage collection algorithm used by the Java VM applies to all objects in the dynamic heap. The algorithm runs
synchronously whenever the heap manager cannot find any memory in the free space list. Or, it may also run asynchronously in
that a thread for the garbage collector is kicked off whenever the system is idle for a sufficient period of time. (This is of
dubious value, as the asynchronous garbage collector will be interrupted and have to start again if a runnable class becomes
ready.) And, you may manually initiate the garbage collection algorithm by calling the method System.gc(). For highly
interactive applications where idle processing may be at a minimum, you might occasionally want to call the garbage collector

The actual garbage collector used by the JVM is an implementation of the stop-and-copy algorithm. But, there is a difference.
Normally, after the garbage collector finishes its compaction phase, all variables and fields that relate to an object would need
to change. But, because all object reference variables are handle based, we don’t need to find and update all variables that
point to active objects. You can simply update the handle in the heap to point to the just-moved object instance. The algorithm
is pretty fast but not ready for real-time applications.

One last aspect to the JVM’s garbage collector is the notion of a Finalizer method. A Finalizer is a special
method called finalize that is declared in the base class java.lang.Object. It has the following prototype:

protected void finalize () throws Throwable;

The finalize method is for cleaning up external resources (such as open files) that would not normally be performed in
routine garbage collection. The garbage collector calls the finalize method just prior to garbage collecting an object
instance. The problem is that garbage collection is not run immediately when you call the System.gc() method; it is
simply scheduled to run. The garbage collector thread runs at a very low priority and may get interrupted frequently. In fact, the
garbage collector may never get to dispose of your object before the application terminates. So, generally speaking, the
usefulness of implementing the finalize method is questionable.

You can do one other trick in a finalize method—”resurrect” an object instance. It is possible for you to place the value
of the this field into some other object reference and stop the object from being garbage collected. At that point, though,
the garbage collector will not call the finalize method again, even when the object instance is really ready for garbage

That’s all there is to heap management in Java: one heap contains a fixed table of class information and methods, and another
heap holds the handle table and object instances. You don’t explicitly deallocate anything (although setting an unused object
variable to null will act as a hint to the garbage collector and heap), and the garbage collector may be run manually by calling
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.


Accepted Solution

mbormann earned 100 total points
ID: 2525966
As u seem to be so inclined u may be interested to know that generally objects are predominantly small (less than 512 bytes or 1kb ?) and short lived. They come and go but their references as they said is stored in another static non garbage collected heap,si in order to simplify the allocation of objects and reduce the amount of time spent doing garbage collection the prcess of allocating objects relatively near each other in space provides better memory behavior and less fragmentation.
hoep now it's clear !
U may also check out the Memory Management reference which has got tons of papers on various topics which u may be interested in

also check out
LVL 16

Expert Comment

ID: 2526307
I suppose that you work with Netscape browser. a well know bug is that when you resize browser window, Netscape JavaVM calls stop() and start() methods on your applet.

since you are still working with the same applet (and FlowLayout()) instance you'll add new Label component on each start() call.

one workaround
add(new Label());

Author Comment

ID: 2526492
The use of the start() method with Netscape was to demonstrate the repeated calls. I wanted to try to understand, for myself, what was going on with the Label objects that were added by those repeated invocations.

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JUnit 4 @Before and @BeforeClass differences 3 58
javap bin 2 34
HashTable highest marks enumeration alternative 9 37
web application structure 18 76
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now