Run-time Internals: The Stack

The stack is a run-time data structure that provides the storage space needed for method calls and returns. All modern block-structured languages use stacks, and many processors have some hardware support for them. Unfortunately in recent years, the terminology has got a little looser; marketing people started using stack to mean any layered system service, such as the TCP/IP library, or an application server and container. In this chapter, stack means the LIFO (Last In First Out) data structure that provides space for local variables, and implements the method-calling conventions.

When you call a method, some housekeeping data, known as an activation record or stack frame, is pushed onto the stack. The activation record contains the return address, the arguments passed to the function, the space for local variables, intermediate calculations, and so on, for that invocation of that method in that thread of control. When you return from a function, the activation record is popped from the stack. The next function call will push another record into the same space.

Figure 10-1 shows how each method call results in a new activation record being pushed onto (added to) the stack. Stacks are only ever meant to be used for data, never for storing code.

Figure 10-1. Stacks in Java

image

Although we have talked about “the stack”, there will actually be one stack allocated for each thread of control within your program. If a thread in your Java code (or any Java libraries you are using) calls out to a C library, another stack will be allocated to hold the C activation records. You don't have to do anything special to get your stacks. As part of instantiating a new thread, the run-time allocates a new stack for it to use. The heap is usually put at the opposite end of the address space to the stacks, and they grow towards the holes between them.

The JDK compiler option -Xoss determines the size of the Java stacks. The default value depends on the hardware you are using, and the JDK version. You can set the value to 64Kb with compiler option: -Xoss64k. If a thread runs out of stack space or collides with the bottom of another stack, you will get the exception java.lang.StackOverflowError. (Sun uses the standard trick of mapping a page at the end of each stack with no permission, so if a thread bumps into it, the OS memory protection catches it at once). This is a good point to pick up with the description of exceptions, starting in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.99.71