Java Memory Management Interview Questions

Java Memory Management Interview Questions  


What is memory leak?

In Java, Garbage collector handles memory management, but when garbage collector is not able to free any object that is not used by the application but it still holds the reference to it is called memory leak.
In other words, when the program/application allocates memory for the object and later when object is no longer needed, instead of marking the reference as null, application holds the indirect reference to that object in such a way that garbage collector cannot free that object is called memory leak. slowly, application memory starts growing and ultimately result in OutOfMemoryError.


What happens when Garbage Collector(GC) runs? what does it mean by "stop-the-world"?
When GC thread runs, other threads are stopped for that duration, so application waits for that duration.
Note: Irrespective of GC need to run in Old generation or New Generation, all the events of GC run will pause application threads until GC run completes.


In Java, what goes in Heap and Stack?

Heap and Stack both are the part of RAM. So there is a separate space in RAM for stack and heap. 
Local variables/references: All the local variables (primitive type) of the method and the method call itself goes to Stack. 

Objects: when an object is created using new operator, the actual space for that object is allocated in heap but the reference to that space(object) is created in stack.
class Student {
    String rollNumber;
    String name
    Address address;
}

class Address{
    String zipcode;
}
public static void main(String args[]){
   Student s1 = new Student(10, "Jason", new Address("V5H3U7"))
}


Stack                     Heap
s1 ----------------> Student{ rollNumber = 10, name="Jason", address}
                                                                                                     |
                                                                                                     |
                                                                              Address{zip code = "V5H3U7"}

What is the scope of Heap and Stack?

The stack is associated for a thread, so when the thread is done the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits.


Which is faster Stack or Heap? Why?

Stack is faster in many terms than Heap though they both are part of RAM. 
For Stack, in terms of deletion, it just needs to move the pointers in LIFO Manner, whereas for Heap, it has to do checks for live references along with that deletion creates fragmentation issues where if memory is freed in non continuous manner, then it has to do compaction (Memory compaction is the process of moving allocated objects together and leaving empty space together.)

Heap is shared across Threads, so allocation/deallocation of memory needs to be synchronized for Heaps, but for Stack, memory is private to Stack. this is also the reason Stack is faster than Heap.

Stack is generally accessed more frequently so for that purpose data of Stack is cached and that is also the reason it is faster than Heap.

The heap is a portion on RAM which is not managed automatically, and is not as tightly managed by the CPU. It is a just a block of memory and need to be managed by user. To allocate memory on the heap, you must use new keyword. we are responsible for deallocation of unused memory once we no longer require it, failing which can cause memory leaks.



How you fine tune Heap size?


-Xms (example: -Xms64m or -Xms64M)
Sets the initial size of the Java heap. 

-Xmx (example: -Xmx1g or -Xmx1G)
Sets the maximum size to which the Java heap can grow. 

-Xmn (example: -Xmn512, -Xmn512m, -Xmn512k)
Sets the initial Java heap size for the Young generation(Eden generation). 

-Xss (example: -Xss512, -Xss512m, -Xss512k)
Sets the maximum stack size of each thread.
This option allows to fine tune max size allocated to each thread to store local variable, partial results and method calling information.
When the method is doing heavy operation with lots of variables, method calls and if you are encountering  StackOverflowError, you can fine tune stack size by using this flag.

-Xnoclassgc
Disables garbage collection (GC) of classes. When you specify -Xnoclassgc at startup, the class objects in the application will be left untouched during GC and will always be considered live. This can result in more memory being permanently occupied which, if not used carefully, will throw an out of memory exception.


When you encounter StackOverflowError and OutOfMemoryError?

StackOverflowError :
Stack is used in Java for method execution, for every method call, a block of memory is created in the stack. The data related to method like parameters, local variables or references to objects are stored in this block.

When the method finishes its execution, this block is removed from the stack along with data stored in it. If a method keep calling other method recursively without returning back then at one point Stack will be full and there would not be any space left for allocating new stack block at that time you will encounter StackOverflowError.

OutOfMemoryError:
When there is no space left for creating new objects on Heap memory, java.lang.OutOfMemoryError  is thrown.


OutOfMemoryError is encountered in below two scenarios, 
1. java.lang.OutOfMemoryError: Java heap space Issue
2. java.lang.OutOfMemoryError: PermGen space Issue

Note few points below: 
1. Garbage collection happens on Heap only.
2. Stack size is private to Thread
3. Heap size is shared across Threads.



How Garbage collection works, What is Mark and Sweep algorithm for garbage collection?  

In Java, GC handles memory management, so it is GC's job to remove the object and free up the heap space when it is no longer referenced.
For removing the object, it first need to scan all the objects present, whether there exist any active references to the object or not, and remove the object those are not referenced from anywhere.

  • The process of identifying and marking the referenced(reachable) object is called Marking phase, where GC starts marking the objects as a indication that they are reachable, that is, the object reference is being referred(in use) and should not be deleted.
  • The process of deleting the marked objects is called Sweep phase, where un-referenced objects  memory are freed up and heap space will be reclaimed. 



Does GC guarantees that a program will not run OutOfMemory?

GC does not guarantee that a program will not run out of memory. It is possible that Program create objects faster as compare to GC cleaning the unreferenced objects. Also, it is possible that application creates lots of heavy object and holding the references to those object in this case GC can't help and may cause OutOfMemory error.


How many Class loaders are present in JVM?

First of all what Class loader does is load the .class files from physical location to JVM's memory and stores information such as class names, parent class, methods, constructors etc.

There are mainly 3 class loaders present in JVM, 

Bootstrap ClassLoader: This classloader prime responsibility is to load internal core java classes present in the rt.jar and other classes present in the java.lang.* package. This class loader is shipped with every JVM and is written in native language. This class loader has no parent classloader.

Extension ClassLoader: This classloader responsibility is to load classes from jre\lib\ext folder.
The parent of this class loader is Bootstrap classloader. Java extensions are also referred to as optional packages.

Application or System ClassLoader: The parent of this class loader is Extension classloader  
and is responsible for loading the classes from the system classpath(generally classes folder). It internally uses the ‘CLASSPATH‘ environment variable and is written in Java language. 

Note: Class is loaded into memory only once even if you try to load multiple times.


When you get NoClassDefFoundError? 

It is an error of type java.lang.Error. Any class which is available while compilation phase but is no longer available while running the application causes NoClassDefFoundError. Example:
class Student{ }
public class MainApp{
    public static void main(String[] args){
        Student stud = new Student();
    }
}
> javac MainApp.java
Above command will generate 2 classes MainApp.class and Student.class
Delete Student.class file
> java MainApp
This will throw NoClassDefFoundError


When you get ClassNotFoundException? 

It is an runtime exception and is caused when application tries to explicitly load any class using Class.forName("path of class") and if the class is not available at the mentioned Path then it throws ClassNotFoundException.


How JVM Heap memory blocks is divided?
Till Java 7
java memory management and garbage collection
Java memory management

Eden space, S0, S1 = Young Generation
S0, S1 = Survivor Space
Old Memory = Old Generation = Tenured Memory
Perm = Permanent Generation

Short description of Heap blocks:

Eden space, S0 and S1 are called Young generation space and Old Memory space is called old Generation space this is because Newly created objects are places in Eden space.

When GC runs in Eden space and if there are live references found in Eden space they are placed into Survivor space S0 and when GC runs in S0 and the reference is still live
(after some threshold) it is placed in S1. Now when GC runs in S1 and the reference is still live (after some threshold of surviving multiple GC cycle) it is placed in Old generation space.

Permanent Generation Space (PermGen space):
This is non Heap space used to store class metadata information. It is used by JVM to describe the classes and methods used in the application.

Note: You can get OutOfMemoryError when any of this block has no further space to store data.

When GC runs at Eden, S0 or S1 space it is called Minor GC, but when it runs in Old Generation it is called Major GC and it takes time to complete GC operation in Old generation . 

Java 8
PermGen space which was part of Heap is removed in Java8 and is now called Metaspace.
The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata, this also means that there will no longer be java.lang.OutOfMemoryError: PermGen space problems.

The arguments which was used to set the PermGen space is now useless and PermSize and MaxPermSize JVM arguments are ignored and a warning is given if present at start-up.

A new flag called MaxMetaspaceSize is provided to limit the amount of native memory used for class metadata. If we don’t specify this, the Metaspace will dynamically re-size depending of the application demand at runtime.

Garbage collection of the dead classes and classloaders is triggered once the class metadata usage reaches the “MaxMetaspaceSize”.



What is Method Area and where it belongs?

Method Area is part of space in the Perm Gen and used to store class structure (runtime constants and static variables) and code for methods and constructors.


Where is Java String pool located?

String pool was part of PermGen space but is now moved to separate Heap space because PermGen space was very limited, default size 64 MB and was used to store class metadata .class files information.


When are static variables loaded in memory ?

They are loaded at runtime when the respective Class is loaded.


What happens when we import any package or class? what if the same import is repeated in multiple classes? Will the JVM load the package or class twice at runtime?

No matter how many times you import the same class. JVM will load class only once(per class loader).


When is the finalize() method called in Java?

The finalize method will be called after the GC detects that the object is no longer reachable, and before it actually reclaims the memory used by the object.

Note: It is not a good practice to rely on finalize() method for clean up operation as we never know when GC will be invoked, also it is not guaranteed. 
Also, finalize method may not get called if there is always active reference to the object.
finalize() is part of Object class.
@Override
public void finalize() {
    try {
        reader.close();
        System.out.println("Closed BufferedReader in the finalizer");
    } catch (IOException e) {
        // ...
    }
}

there are chances that class A job is to read data from file and then cache the String and always returned cached value, in this case we only need to open connection to file, read it and close. if we use finalize for closing the connection would be bad here because class A instance may always have active reference to return the cached value and finalize for closing the file will never get invoked.



Do member(instance) and local(method) variables have default values?

Example:
public class Example {
    static int a;
    int b;

    void getA(){
        A ref;
        int c ;
        System.out.println(a);   // ok         
        System.out.println(b);   // ok         
        System.out.println(ref); //Error: Variable ref might not have been initialized            
        System.out.println(c);   //Error: Variable c might not have been initialized    
   }
}


All member variables have to load into heap so they have to initialized with default values when an instance of class is created, so member variables are initialized with default values.
Local variables are stored on stack, so they are not initialized by default.


When the class is loaded by classloader?

When the class object is created using the new operator (static class loading) or when the class is explicitly loaded using Class.forName("path of the class") (dynamic class loading).


What are strong, soft, weak and phantom references in Java?


These references are useful in terms of when they are eligible for Garbage collection.

Strong Reference:
This is the default behavior of object creation. Strong reference means the object should not be garbage collected if there is any live reference pointing to it.

Student s = new Student()
s.rollNo = 10;
                                                              GC
                                                             ---------------------------
s------------------------------------------->| Student(rollNo=10)  | Heap
                                                              --------------------------
                                                              GC will not remove this memory because it is referred by                
                                                               strong reference "s"    

Weak Reference:
A weak reference is a reference which is not strong enough to survive garbage collection. In simple words, as the name suggest, object created using weak reference will be weak enough to get removed when the next garbage collection cycle runs.

Soft Reference:
A soft reference is very similar to Weak reference but the only difference is GC will throw the soft reference only when memory is low. It is generally used for implementing Cache.

Phantom reference:
A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want to be notified that an object is about to be collected.



What are different ways to create String object? Explain.

There are 2 ways to create String object,
1. String str1 = new String("javabypatel");
2. String str2 = "javabypatel";

With the first approach using new operator, JVM creates the String in Heap as well as in String literal Pool (However I found conflicting answers for this, where some claims that only one object is created in heap and we need to explicitly call intern() method to copy it to pool), str1 will refer to the object created in Heap.

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.



How substring() method of String class use to create memory leaks before Java 7?

We know memory leak happens when application is not using a object and GC is not able to reclaim memory blocked by that object due to active reference still exist.
substring method creates scenario as described above which leads to Memory leak.

Detail explanation in this How substring method creates memory leak in Java



What is Just-in-time(JIT) compilation in Java?

1. In Java, .java files are compiled to byte code(.class file)
2. JVM reads the .class files and convert it into machine understandable format.
3. Machine understandable lines are passed to CPU for execution.

Example source code:
String str1 = "Hello, this is Java";
System.out.println(str1);
System.out.println(str1);
System.out.println(str1);

Above code is compiled and say .class file is generated like below,

xyz1111
mnooooo
mnooooo
mnooooo

JVM needs to load compiled .class file, converts each line into Machine understandable format and give it for execution.

Before converting the compiled .class files to machine understandable instructions, JVM takes the compiled class files and does further compilation for complex optimizations to generate high-quality machine code. we will see what kind of optimization it does later. (this further compilation is done by part of JVM which is known at JIT.)

From above example, is there need to convert byte code "mnooooo" 3 times?
No. converted code can be stored and can be reuse when required.

JIT Compiler helps doing such optimization for JVM.

JIT also does further compilation to .class files and one of the feature for which it does further compilation is inlining, which is the practice of substituting the body of a method into the places where that method is called. Inlining saves the cost of calling the method; no new stack frames need to be created. By default, Java HotSpot VM will try to inline methods that contain less than 35 bytes of JVM bytecode.

Loop optimization, type sharpening, dead-code elimination, and intrinsics are just some of the other ways that Java HotSpot VM tries to optimize code as much as it can. Techniques are frequently layered one on top of another, so that once one optimization has been applied, the compiler might be able to see more optimizations that can be performed.

Compilation Modes
Inside Java HotSpot VM, there are actually two separate JIT compiler modes, which are known as C1 and C2. C1 is used for applications where quick startup and rock-solid optimization are required; GUI applications are often good candidates for this compiler. C2, on the other hand, was originally intended for long-running, predominantly server-side applications. Prior to some of the later Java SE 7 releases, these two modes were available using the -client and -server switches, respectively.


When memory is allocated for static variables in java?

When the class is first loaded into memory.


Where does static method, variables are stored in Java?


Classes goes in special area on heap called Permanent Generation.
Static member variables are kept on the Permanent Generation.
Eg:
static int i =10 (i=10 goes in perm gen space.)

static Address address = new Address
(address = "pointer to where address object is created" address reference will be part of permgen space but the actual memory allocation [new Address()] can be in Young or Old generation in Heap.)

static method(code): There is only one copy of each method per class, be the method static or non-static. That copy is put in the Permanent Generation area. (Method Area part of PermGen space)

You may also like to see


Level Order Traversal of Binary Tree.

Advanced Multithreading Interview Question-Answer

Traverse a Binary Tree in Level Order Traversal

Serialize and Deserialize a Binary Tree

Find diameter of Binary Tree

How Much Water Can a Bar Graph with different heights can Hold

Interview Question-Answer on Java

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment