Showing posts with label heap-memory. Show all posts
Showing posts with label heap-memory. Show all posts

Friday, 24 June 2011

How different variables stored in java - on Heap and stack

  • Instance variables and objects live on the heap.
  • Local variables live on the stack.

Let’s take a look at a Java program, and how its various pieces are created and map into the stack and the heap:

1. class Cub{ }
2.
3. class Lion {
4. Maine c; // instance variable
5. String name; // instance variable
6.
7. public static void main(String [] args) {
8.
9. Lion d; // local variable: d
10. d = new Lion();
11. d.go(d);
12. }
13. void go(Lion lion) { // local variable: Lion
14. c = new Cub();
15. lion.setName("Bakait");
16. }
17. void setName(String LionName) { // local var: LionName
18. name = LionName;
19. // do more stuff
20. }
21. }

  This is how the variables and methods get placed in the stack and heap during execution of the above piece of code.
  • Line 7—main() is placed on the stack.
  • Line 9—reference variable d is created on the stack, but there’s no Lion object yet.
  • Line 10—a new Lion object is created and is assigned to the d reference variable.
  • Line 11—a copy of the reference variable d is passed to the go() method.
  • Line 13—the go() method is placed on the stack, with the Lion parameter as a local variable.
  • Line 14—a new Maine object is created on the heap, and assigned to Lion’s instance variable.
  • Line 17—setName() is added to the stack, with the LionName parameter as its local variable.
  • Line 18—the name instance variable now also refers to the String object.
  • Notice that two different local variables refer to the same Lion object.
  • Notice that one local variable and one instance variable both refer to the same String Aiko.
  • After Line 19 completes, setName() completes and is removed from the stack. At this point the local variable LionName disappears too, although the String object it referred to is still on the heap.

Monday, 25 April 2011

Playing with JVM heam size

Java programs executes in JVM uses Heap of memory to manage the data. If your Java program requires a large amount of memory, it is possible that the virtual machine will begin to throw OutOfMemoryError instances when attempting to instantiate an object. The default heap size if 1 MB and can increase as much as 16 MB.

Java heap space setting from command line:
  1. -Xms for initial heap size
  2. -Xmx for maximum heap size 
  3. -Xss<size>   for set java stack size
     


Initial heap size 128m, max heap size 256m:
java -Xms128m -Xmx256m MyApp


Initial heap size 256m, max heap size 256m:
java -Xms128m -Xmx256m MyApp


Max heap size can't be less than initial heap size:
java -ms256m -mx128m MyAppError occurred during initialization of VM
Incompatible initial and maximum heap sizes specified

Saturday, 16 April 2011

Address of a Java Object

Java has no pointers, but still there are methods which let us know address of objects.
Unsafe is a class that belongs to sun.misc package, to which may be you are new.

When a class name is “Unsafe” in java, it calls for your attention immediately. Then I decided to dig deep into it and find what is unsafe about that class. Its difficult to find the source of Unsafe. Get the source and look at the methods you will know what I am referring to.

Java’s security manager provides sufficient cover and ensures you don’t fiddle with memory that easily. As a first step, I thought of getting the memory location of a java object. But lets see.

Sun’s Unsafe.java api documentation shows us an opportunity to get the address using the method objectFieldOffset. That method says, “Report the location of a given field in the storage allocation of its class“. It also says, “it is just a cookie which is passed to the unsafe heap memory accessors“. Whatsoever, I am able to get the storage memory location of an object from the storage allocation of its class.

You can argue that, what we have got is not the absolute physical memory address of an object. But we have got the logical memory address. The following program will be quite interesting for you!
The program had following steps:

  • As a first step, I have to get an object of Unsafe class. It is quite difficult as the constructor is private. 
  • There is a method named getUnsafe which returns the unsafe object. Java’s security manager asks you to make your java source code privileged. I used little bit of reflection and got an instance out. I know there are better ways to get the instance. But to bypass the security easily I chose the following.
  • Using Unsafe’s object just invoke objectFieldOffset and staticFieldOffset. The result is address / location of object in the storage allocation of its class.

Following example program runs well on JDK 1.6:

import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class ObjectLocation {
private static int apple = 10;
private int orange = 10;
public static void main(String[] args)throws Exception {
Unsafe unsafe = getUnsafeInstance();
Field appleField = ObjectLocation.class.getDeclaredField("apple");
System.out.println("Location of Apple: "
+ unsafe.staticFieldOffset(appleField));
Field orangeField = ObjectLocation.class.getDeclaredField("orange");
System.out.println("Location of Orange: "
+ unsafe.objectFieldOffset(orangeField));
}
private static Unsafe getUnsafeInstance()throws SecurityException,
NoSuchFieldException, IllegalArgumentException,
IllegalAccessException {
Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafeInstance.setAccessible(true);
return (Unsafe) theUnsafeInstance.get(Unsafe.class);
}
}

JVM - heap, non heap memory and other terminologies

Java has only two types of memory when it comes to JVM. Heap memory and Non-heap memory. All the other memory jargons you hear are logical part of either of these two.

Heap Memory
In lay man's term class instances and arrays are stored in heap memory. Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data.

Some points to consider:

The Java virtual machine has a heap that is shared among all Java virtual machine threads. The heap is the runtime data area from which memory for all class instances and arrays is allocated.


The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated.
The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary. The memory for the heap does not need to be contiguous.
A Java virtual machine implementation may provide the programmer or the user control over the initial size of the heap, as well as, if the heap can be dynamically expanded or contracted, control over the maximum and minimum heap size.

Non-heap Memory
It comprises of ‘Method Area’ and other memory required for internal processing. So here the major player is ‘Method Area’.

Method Area
As given in the last line, method area is part of non-heap memory. It stores per-class structures, code for methods and constructors. Per-class structure means runtime constants and static fields.

The above three (heap memory, non-heap memory and method area) are the main jargon when it comes to memory and JVM. There are some other technical jargon you might have heard and I will summarize them below.

Memory Pool
Memory pools are created by JVM memory managers during runtime. Memory pool may belong to either heap or non-heap memory.

Runtime Constant Pool
A run time constant pool is a per-class or per-interface run time representation of the constant_pool table in a class file. Each runtime constant pool is allocated from the Java virtual machine’s method area.

Java Stacks or Frames
Java stacks are created private to a thread. Every thread will have a program counter (PC) and a java stack. PC will use the java stack to store the intermediate values, dynamic linking, return values for methods and dispatch exceptions. This is used in the place of registers.
Definition of stack:

Each Java virtual machine thread has a private Java virtual machine stack, created at the same time as the thread. A Java virtual machine stack stores frames. A Java virtual machine stack is analogous to the stack of a conventional language such as C: it holds local variables and partial results, and plays a part in method invocation and return. Because the Java virtual machine stack is never manipulated directly except to push and pop frames, frames may be heap allocated.


See more on frames


Memory Generations
HotSpot VM’s garbage collector uses generational garbage collection. It separates the JVM’s memory into and they are called young generation and old generation.

Young Generation
Young generation memory consists of two parts, Eden space and survivor space. Shortlived objects will be available in Eden space. Every object starts its life from Eden space. When GC happens, if an object is still alive and it will be moved to survivor space and other dereferenced objects will be removed.

Old Generation – Tenured and PermGen
Old generation memory has two parts, tenured generation and permanent generation (PermGen). PermGen is a popular term. We used to error like PermGen space not sufficient.
GC moves live objects from survivor space to tenured generation. The permanent generation contains meta data of the virtual machine, class and method objects.

Discussion:
Java specification doesn’t give hard and fast rules about the design of JVM with respect to memory. So it is completely left to the JVM implementers. The types of memory and which kind of variable / objects and where they will be stored is specific to the JVM implementation.


Key Takeaways

  • Local Variables are stored in Frames during runtime.
  • Static Variables are stored in Method Area.
  • Arrays are stored in heap memory.


References: