JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

JVM Memory Management

February 5, 2016 by Krishna Srinivasan Leave a Comment

Introduction to Java Memory Management

In this article I am going to explain more about the JVM memory management inside Java Virtual Machine (JVM). If you are a Java developer, understanding the Java memory management inside JVM will be much helpful on investigating performance issues related to memory leak, garbage collection, etc. which are critical to production grade applications.

The following are the list of segments inside Java Virtual Machine (JVM) for storing the runtime data required for the application execution. At the end of this tutorial you will be able to understand how JVM allocates memory and what are the important commands for sending instructions to JVM for the memory allocation. If you have any questions related to JVM or you are facing issue like memory leak, please post it in the comments section.

The following are key memory segments inside a JVM:

  1. Program Counter (PC) Register
  2. Method Area
  3. Heap
  4. Java Stack
  5. Native Stack

JVM Memory Allocation

Program Counter (PC)

One of the memory area allocated by JVM is program counter (PC). This segment stores the memory address of the Java Virtual Machine (JVM) instructions currently being executed. A program counter is created every time a new thread is created. Program counter keeps a pointer to the current statements that is being executed in the current thread. If the current executing method is a native method, the counter register will be undefined.

Method Area

Method area inside JVM used for storing the type / class information. When first time running a Java application, classloader will tries to load the classes by using the fully qualified name of each classes. Classloader will read the class file as stream of binary data and store the details inside method area. Method area is also responsible for allocating the memory to store the class / static variables. Method area is common for all the threads, so it must be designed to be thread safe.

The memory of the method area could be allocated on JVM’s own heap. It is up to the implementation decision and not mandated by the specification. The method area also can be garbage collected. If a class becomes unreferenced, a JVM can unload the class to keep the memory occupied by the method area at a minimum.

The following are the other list of details that are stored in method area:

Type Information

The following are the list of type information stored inside method area:

  • The fully qualified name of the type
  • The fully qualified name of the type’s direct superclass (unless the type is an interface or class java.lang.Object, neither of which have a superclass)
  • Whether or not the type is a class or an interface
  • The type’s modifiers

The Constant Pool

A method area has a constant pool where it stores the literals like String, number, etc. and symbolic references to types, fields and methods. All the data stored in the constant pool is referenced using an index similar to an array. This constant pool is acting as the central location for dynamic linking of Java programs.

Field Information

The following details about fields are stored in the method area. Apart from that it stores the order in which the fields are declared by the class or interface also recorded in memory.

  • Field Name
  • Field Type
  • Field Modifiers

Method Information

The following details about methods are stored in the method area. Apart from that it stores the order in which the methods are declared by the class or interface also recorded in memory.

  • Method Name
  • Method return type or void
  • The number of parameters
  • The type of parameters in order
  • The method’s modifiers

Java Stack

Java stack is the memory portion used by the JVM threads to store the thread specific data. Stack memory is not shared among all the threads and it is created for each thread separately. Any data related to a method like local variables, object references to heap are stored in the stack memory. When ever a thread enters a new method, a new block called as stack frame will be created inside stack memory for storing the method specific details. When the thread completes the execution of that method, corresponding stack frame will be pushed out of the stack memory. The total memory allocated for stack is very less compared to the heap memory.

If the current stack memory is not enough for holding the method data (this happens if the method have recursive operation), JVM will throw java.lang.StackOverflowError error. If you are getting this error, you have to increase the stack memory or analyse the program whether it uses any recursive calls by mistake. Deep recursions also can cause StackOverflow errors.

How to increase stack memory?

Developer can change the stack memory size by using the -Xss command. This size is the individual thread’s stack size. That means each thread will have the same amount of memory allocated for their operations.Many Java Virtual Machine publishers set the default size of a thread’s call stack to 256KB.

Java Heap

If your application creating new objects or using arrays, then all the instances are stored in the heap memory of the Java Virtual Machine (JVM). Heap is the primary storage inside JVM for storing the runtime data that are accessed by the multiple threads. Heap memory is the common for all the threads, the data stored in the heap is accessible to all the threads running on JVM.

If the maximum size of the heap is utilized by the JVM, then garbage collector will be triggered for claiming the memory from the unused objects inside heap. Note that, application developer has not control on garbage collector.

Heap memory has the two logical portion based on the lifetime of every objects. First one is Young Generation and second one is Old Generation.

Young Generation:

Heap memory creates new objects in the portion called as young generation. This portion is dedicated for storing the young objects which are very newly created by the Java applications.

Old Generation:

This is another logical portion inside heap memory for storing the older objects. When new objects are created, that are reside inside young generation portion for certain period of time, after that those objects will be pushed to the old generation portion. Objects which are survived from garbage collector for few times will be promoted to the old generation.

If the total allocated memory is not sufficient for storing the new objects, then JVM will throw a java.lang.OutOfMemoryError. Application developers can customize the memory allocation for heap inside JVM by passing the following parameters:

JVM Heap Settings:

  • -Xmx<size> : Maximum heap size allocated
  • -Xms<size> : Initial heap size allocated
  • -Xmn<size> : Size of the young generation objects storage inside heap. This parameter is not used most of the times.

JVM Heap Size

Native Method Stack

Similar to the Java stack, there is a Native Method Stack for storing the thread data for native method calls. This native method stack is available only if the JVM supports the native method calls. Otherwise there is no need for having the native method stack. Memory size is managed similar to general JVM stacks like fixed or dynamic. This is created for per thread basis and can not be shared among all the threads. If the native method stack is full and don’t have the enough memory to store the new data, then JVM will throw StackOverflowError or OutOfMemoryError accordingly.

I hope this tutorial provide good amount of information about the JVM memory allocation. If you have any questions, please write it in the comments section.

Filed Under: Java Tagged With: JVM

How To Get JVM Start Time And Date

March 17, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to get the start time and date for the current execution environment of Java Virtual Machine (JVM). RuntimeMXBean in the Java lang package helps in getting the details of the JVM start time. By invoking the method getStartTime() in RuntimeMXBean class, it returns the time in long number which can be converted to a integer. Lets look at this example for more clarity.

[code lang=”java”]
package javabeat.net.core;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Date;
/**
* JVM Start Time and Date Example
* @author krishna
*
*/
public class JVMStartTimeExample {
public static void main(String args[]) {
// Get JVM’s system thread
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
// Get start time
long startTime = runtimeMXBean.getStartTime();
// Get start Date
Date startDate = new Date(startTime);
// print values
System.out.println("JVM Start Time = " + startTime);
System.out.println("JVM Start Date = " + startDate);
}
}
[/code]

Output

[code]
JVM Start Time = 1395039166075
JVM Start Date = Mon Mar 17 12:22:46 IST 2014
[/code]

The above example displays the JVM start time and date details.

Filed Under: Java Tagged With: Java Lang, JVM

How To Set Tomcat JVM Heap Size in Eclipse?

November 28, 2013 by Krishna Srinivasan Leave a Comment

If JVM head size for Tomcat is not enough, you would get the error java.lang.OutOfMemoryError. If you are using eclipse, it is easy to increase the available heap size by using the server configurations. Look at the below steps to configure the VM arguments passed to JVM for running the tomcat server.

1. Open Server Configuration

Double click on the server name to open the configurations.

Tomcat in Eclipse

2. Open Launch Configuration

Click on the Open launch configuration to open the configuration properties.

Tomcat Configurations

3. Update VM Arguments

Go to Arguments tab and add the JVM arguments to the field “VM arguments”.

eclipse-tomcat-3

Filed Under: Eclipse Tagged With: heap size, JVM, memory, Tomcat

What is the difference between JRE,JVM and JDK?

February 21, 2013 by Krishna Srinivasan Leave a Comment

If you are a Java developer, it is very often that you think about understanding the JRE,JVM and JDK. Once if you understand these things, it would be quite easy for you to visualize things in logical manner. Also look at the picture below, that will clear all your questions about the JRE,JVM and JDK. This article explains about the each term and will make you understand perfectly. Hope this helps. If you are happy to receive our future updates on Java, please subscribe here.

JDK (Java Development Kit)

Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc… Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method.

You need JDK, if at all you want to write your own programs, and to compile the m. For running java programs, JRE is sufficient. JRE is targeted for execution of Java files i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries. JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file.

  • Java Annotations
  • Java Generics

JRE (Java Runtime Environment)

Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system

JVM, JRE and JDKThe Java Virtual Machine provides a platform-independent way of executing code; programmers can concentrate on writing software, without having to be concerned with how or where it will run. But, note that JVM itself not a platform independent. It only helps Java to be executed on the platform-independent way. When JVM has to interpret the byte codes to machine language, then it has to use some native or operating system specific language to interact with the system. One has to be very clear on platform independent concept. Even there are many JVMs written on Java, however hey too have little bit of code specific to the operating systems. 

If u just want to run applets (ex: Online Yahoo games or puzzles), JRE needs to be installed on the machine.

JVM (Java Virtual Machine)

As we all aware when we compile a Java file, output is not an ‘exe’ but it’s a ‘.class’ file. ‘.class’ file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.

The JVM is called “virtual” because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.

There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.

Reference:

  • JVM Specification
  • JVM Internals by James D Bloom

Recommended Books:

  • Head First Java
  • Java : The Complete Reference

Filed Under: Java Tagged With: Java, JRE, JVM

JVM,JRE,Java Compiler Interview Questions

August 5, 2010 by Krishna Srinivasan Leave a Comment

JVM,JRE,Java Compiler FAQs-1

1)How can I write a program that takes command line input?

A: Java programs that take input from the command line declare a special static method called main, which takes a String array as an argument and returns void. The example program below loops through any arguments passed to the program on the command line and lists their values.

2)What does public static void main(String[]) mean?

A: This is a special static method signature that is used to run Java programs from a command line interface (CLI). There is nothing special about the method itself, it is a standard Java method, but the Java interpreter is designed to call this method when a class reference is given on the command line, as below.

3)Why are command line arguments passed as a String?

A: Command line arguments are passed to the application’s main method by the Java runtime system before the application class or any supporting objects are instantiated. It would be much more complex to define and construct arbitrary object types to pass to the main method and primitive values alone are not versatile enough to provide the range of input data that strings can. String arguments can be parsed for primitive values and can also be used for arbitrary text input, file and URL references.

4)Why doesn’t the main method throw an error with no arguments?

A: When you invoke the Java Virtual Machine on a class without any arguments, the class’ main method receives a String array of zero length. Thus, the method signature is fulfilled. Provided the main method does not make any reference to elements in the array, or checks the array length before doing so, no exception will occur.

5)Why do we only use the main method to start a program?

A: The entry point method main is used to the provide a standard convention for starting Java programs. The choice of the method name is somewhat arbitrary, but is partly designed to avoid clashes with the Thread start() and Runnable run() methods, for example.

6)Can the main method be overloaded?

A: Yes, any Java method can be overloaded, provided there is no final method with the same signature already. The Java interpreter will only invoke the standard entry point signature for the main method, with a string array argument, but your application can call its own main method as required.

7)Can the main method be declared final?

A: Yes, the static void main(String[]) method can be declared final.

8)I get an exception if I remove the static modifier from main!

A: The static void main(String[]) method is a basic convention of the Java programming language that provides an entry point into the runtime system. The main method must be declared static because no objects exist when you first invoke the Java Virtual Machine (JVM), so there are no references to instance methods. The JVM creates the initial runtime environment in which this static method can be called, if you remove the static modifier, it will throw a NoSuchMethodException.

9)How can the static main method use instance variables?

A: For very simple programs it is possible to write a main method that only uses static variables and methods. For more complex systems, the main method is used to create an instance of itself, or another primary class, as the basis of the application. The primary application object reference uses instance methods to create and interact with other objects, do the work and return when the application terminates.

[code lang=”java”]public class SimpleClass {

public void doSomething() {

// Instance method statements
}

public static main(final String[] args) {

SimpleClass instance = new SimpleClass();

instance.doSomething();
}
}[/code]

10)main method from another class?

A: Yes, the main method can be called from a separate class. First you must prepare the string array of arguments to pass to the method, then call the method through a static reference to the host class, MaxFactors in the example below.

[code lang=”java”]String[] arguments = new String[] {"123"};

MaxFactors.main(arguments);
[/code]

11)What is the source code for the compiler?

A: The source code for a Java program is also known as a compilation unit, which contains the code for a top level Java class or interface. A Java compilation unit is usually created in the form of a file with a .java extension and is passed to the compiler as a file path reference.

The Java source file contains a header that declares the type of class or interface, its “visibility” with respect to other classes, its name and any superclass it may extend, or interface it implements. The body of the class contains variable declarations and methods that define the behaviour of the class, and any constructors used to create an instance of the class. A compilation unit may also contain nested inner classes.

12)Why is the source file named after the class?

A: The Java source file naming convention is not a standard specified by the Java language but is a common feature of Java compilers, such as javac, to help locate source code. The source content of a Java class is known as a compilation unit. By storing the compilation unit in a file that is named after the class, the compiler can locate any supporting classes by name and compile those too.

This convention also extends to package names. Most Java compilers expect source code to be stored in directories whose names match their package hierarchy. Thus the source code for a class named Example in the package com.domain.util might be stored in a file with the path c:\src\com\domain\util\Example.java

13)Which class should be compiled first?

A: Sometimes you will find that trial and error will give you the answer you need. If you are using the Sun compiler, javac, the compiler will compile any other classes that your target class depends on, provided the other source files are in the same directory hierarchy as the first and the sub-directory names reflect the package hierarchy of the classes.

14)What are the steps in compiling a class?

Once you have written the Java source code file, there is only one step required to compile it. To compile the class from the command line, you need to give the path to the compiler program, such as Sun javac, and the path of the source code file, like this:

15)Where is my compiled class file?

A: If you are sure your class is being compiled, then the class file should be output somewhere! Without any directory argument, your compiler should place the class file in the same directory as your source file. Use the output directory argument to specify where the class files are generated.

16)How can I ensure my compiler will locate the SAX package?

A: One way to ensure your compiler can locate any package it may require is to pass its path to the compiler explicitly using the -classpath argument.

17)What does this deprecation message mean?

A: The deprecation message you have seen means that the methods you are calling have been marked with a JavaDoc deprecation comment. When a method or class is marked deprecated it is only advisory, not mandatory, but the advice is given for good reason and should be followed. So long as deprecated methods remain in the public API it is possible to use them, so this approach supports legacy code and gives developers time to amend their applications as necessary.

18)What are undefined and undeclared variables?

A: One gets warning messages about undefined and undeclared variables when compiling Java classes that have programming errors, as in the example below.

19)Why doesn’t the compiler warn about stack overflow problems?

A: There are many cases of poor runtime programming that could potentially be identified at compile time, but the number and subtlety of the cases gets increasingly difficult to address. The main purpose of a compiler is to produce executable byte code that is valid according to the rules of the programming language, not to guard against poor programming. Hence most compilers only validate the syntax of the language and the most obvious logical errors in the code at compile time.

20)How do I set environment variables on Windows XP?

A: For Windows 2000/XP systems, the environment settings are edited in a special Control Panel applet called System.

21)How do I set the compiler path?

A: The Java compiler is a program like any other and your operating system needs to know where to find the executable file. The simplest way to do this is to give the full path to the Java compiler in the command, as below for Windows…

22)How do I configure EditPlus to compile Java and capture output?

A: These instructions on configuring the NSGMLS markup validator for EditPlus will help you get started. For Java, the Command field will be the path to your javac.exe program (or java.exe to run). The Argument should contain any parameters you want to pass to the compiler and should end with the $(FilePath) variable that substitutes the current file name. Check the Capture output box to get feedback from the compiler.

Filed Under: Interview Questions Tagged With: JRE, JVM

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved