Differentiate between the stack and heap ?
The differentiation between stack and heap are as follows :
1.To store local variables and function call the stack memory is used, while to store objects in Java heap memory is used. Yet, where object is created in code such as member variable, class variable or local variable they are created always inside heap space in Java.
2. Each and every thread in Java has their own stack that can be specified using -Xss JVM parameter, thus also specify the heap size of a Java program by using JVM option -Xms and -Xmx where -Xms is starting size of heap while -Xmx is maximum size of java heap.
3. If no memory left in stack for storing function call or local variable, JVM throw java.lang.StackOverFlowError, but if there is no more heap space for creating object, JVM throw java.lang.OutOfMemoryError.
4. Using Recursion, on which the method calls itself, fill up rapidly the stack memory. Now other difference is that size of stack memory is lesser in comparison to the size of heap memory.
5.Variables that are stored in stacks are visible to the partner thread only, but objects created in heap are visible to all the thread. On the other hand, stack memory is kind of special memory but heap memory is shared among all the threads.
How can you define the size of the heap for the JVM ?
The JVM provides several command-line arguments for defining the size of the memory allocated to the different memory areas.
When starting up the JVM, specify the maximum heap size with the command-line flag -Xmx and a size. For an example, starting the JVM with java -Xmx512M <classname> creates a JVM with a maximum heap size of 512 megabytes. And the suffixes for the memory size are G for gigabytes, M stands for megabytes, or K for kilobytes.
It is important to note that the JVM will not allocate this memory in its entirety on startup.It will grow to a maximum of that size only if needed.
To specify the initial amount of memory allocated to the JVM, use the -Xms argument. It works in the same way as -Xmx. This argument is advisable to need a certain amount of memory for function, as it will save application from excessive slow garbage
collections before expanding to required size.
If both arguments are set to the same value, the JVM will ask the operating system for that full memory allocation on startup, and it will not grow any larger.
For the initial memory allocation, the default value is 1/64 of the memory. For the maximum default, it is the smaller of 1 GB and a quarter of the computer’s physical memory.