Q. What is memory management in Java and types of memory?
In Java, memory management is a key aspect that involves understanding different types of memory and how Java handles them. Here are the main types of memory in Java:
Memory Type | Purpose | Characteristics |
---|---|---|
Heap Memory | The Java heap is a crucial runtime data area where memory allocation for all class instances and arrays occurs. This is where Java objects are dynamically allocated during program execution. | It is divided into two parts, the Young Generation (which includes Eden Space and Survivor Spaces) and the Old Generation (also known as the Tenured Generation). |
Stack Memory | This memory is used for storing local variables and method call information. Each thread in a Java application has its own stack. | Stack memory, organized as a stack data structure, creates a stack frame for each method call, holding local variables and partial results. It is automatically managed and deallocated upon method completion. |
Method Area (or Metaspace) | This area stores class-level data such as class structures, method data, and runtime constant pool information. In Java 8 and later, the Method Area is implemented as Metaspace. | Metaspace grows automatically by default, but you can configure its maximum size. It was previously known as the Permanent Generation (PermGen) in earlier Java versions. |
Native Method Stack | This memory is used for native method calls, which are methods written in languages other than Java, like C or C++. | It is specific to JVM implementations and is used to support interactions with native libraries. |
Program Counter (PC) Register | This is a small amount of memory that holds the address of the currently executing instruction. It helps the JVM to keep track of the execution flow. | Each thread has its own PC register to maintain the execution context of the thread. |
Runtime Constant Pool | Part of the Method Area, the Runtime Constant Pool contains constants referenced by classes and methods (like string literals and numeric constants). | It is used during runtime to support the execution of bytecode instructions. |
Java 8 Memory Management
- Heap Memory:
- Young Generation: Allocates new objects. It includes Eden Space and two Survivor Spaces (S0 and S1). It is collected using Minor Garbage Collection (GC).
- Old Generation (Tenured Generation): Holds long-lived objects and is collected using Major Garbage Collection (Full GC).
- Permanent Generation (PermGen): Stores class and method metadata. In Java 8, it has a fixed size, which can lead to
OutOfMemoryError
if not managed.
- Garbage Collection (GC):
- Serial GC: Uses a single thread for both Minor and Major GC, suitable for smaller applications.
- Parallel GC: Uses multiple threads to improve GC efficiency on multi-core machines.
- Concurrent Mark-Sweep (CMS) GC: Aims to minimize pause times by performing most GC work concurrently with application threads.
- PermGen vs. Metaspace:
- Metaspace (Java 8+): Replaces PermGen, residing in native memory and dynamically resizing as needed, avoiding fixed size constraints and
OutOfMemoryError
related to class metadata.
- Metaspace (Java 8+): Replaces PermGen, residing in native memory and dynamically resizing as needed, avoiding fixed size constraints and
Latest Java Versions (Java 9 and Beyond)
- Heap Memory:
- Young Generation and Old Generation: Similar to Java 8, with improvements in GC algorithms.
- Metaspace:
- Continues to replace PermGen, dynamically managing class metadata without fixed size limits.
- Garbage Collection (GC):
- G1 GC: Introduced in Java 7, improved in Java 8 for predictable pause times by dividing the heap into regions.
- ZGC (Java 11): Low-latency collector aiming for minimal pause times.
- Shenandoah GC (Java 12): Focuses on low-latency and reduced pause times.
- Epsilon GC (Java 11): No-op collector for performance testing.
- Improved GC Algorithms:
- Concurrent and Parallel Enhancements: Better handling of multi-core processors and large heaps.
- Predictability and Performance: Improvements in G1, ZGC, and Shenandoah for better performance and reduced GC pause times.
- Java 21 and Beyond:
- Ongoing improvements in garbage collectors and support for large heaps and real-time applications.
G1 Garbage Collector Improvements in Java 17
- Predictable Pause Times:
- Region-based Collection: Divides the heap into regions for manageable collection chunks, enhancing pause time control.
- Concurrent Work: Performs most work concurrently with application threads for minimal impact.
- Incremental Improvements:
- Adaptive Sizing: Adjusts region and heap sizes based on application behavior.
- Enhanced Mixed Collection: Optimizes collection of both young and old generations together.
- Improved Compaction:
- Efficient Object Relocation: Reduces fragmentation and improves memory utilization.
- GC Pause Time Goals:
- Pause Time Target: Allows specification of a maximum pause time goal to improve predictability.
- Concurrent and Parallel Processing:
- Parallelism: Uses multiple threads for collection processes.
- Concurrent Marking: Reduces pause times with concurrent marking phases.
- Garbage Collection Logging and Monitoring:
- Improved Visibility: Enhanced logging and monitoring for better GC performance understanding.
- Large Heap Optimization:
- Efficient Handling: Manages large heaps more effectively, reducing pause times.
Q. Differences Between PermGen and Metaspace?
Category | PermGen | Metaspace |
---|---|---|
Purpose and Usage | Fixed-size space in the heap for class and method metadata, prone to OutOfMemoryError . | Dynamically grows in native memory, avoiding fixed size constraints and OutOfMemoryError . |
Memory Management | Fixed size, requires manual adjustment. | Dynamically resizes, uses native memory, and is managed automatically. |
Garbage Collection | Less efficient class unloading, can lead to long pauses. | More efficient with class unloading, less impact on application performance. |
Configuration and Monitoring | Specific size configuration needed. | Easier to manage and monitor with dynamic sizing. |
Error Handling | Common OutOfMemoryError due to fixed size. | Less frequent OutOfMemoryError , typically due to memory leaks. |
Q. Difference between Young Generation vs. Old Generation?
Category | Young Generation | Old Generation |
---|---|---|
Purpose | Allocates new, short-lived objects and is frequently collected (Minor GC). | Stores long-lived objects and is less frequently collected (Full GC). |
Structure | Includes Eden Space and Survivor Spaces. | A single contiguous area for long-lived objects. |
Garbage Collection | Frequent, quick collections. | Less frequent, more comprehensive collections with potential for compaction. |
Characteristics | Handles short-lived objects, reducing overall performance impact. | Manages long-lived objects, which can be more challenging to handle efficiently. |
Q. What are the new futures in Java 8?
Q. Difference between abstract class and Interface in java?
Answer: Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can’t be instantiated. But there are many differences between abstract class and interface that are given below.
Abstract class | Interface |
---|---|
1) Abstract class can have abstract and non-abstract methods. | Interface can have only abstract methods. Since Java 8, it can have default and static methods also. |
2) Abstract class doesn’t support multiple inheritance. | Interface supports multiple inheritance. |
3) Abstract class can have final, non-final, static and non-static variables. | Interface has only static and final variables. |
4) Abstract class can provide the implementation of interface. | Interface can’t provide the implementation of abstract class. |
5) The abstract keyword is used to declare abstract class. | The interface keyword is used to declare interface. |
6) An abstract class can extend another Java class and implement multiple Java interfaces. | An interface can extend another Java interface only. |
7) An abstract class can be extended using keyword “extends”. | An interface can be implemented using keyword “implements”. |
8) A Java abstract class can have class members like private, protected, etc. | Members of a Java interface are public by default. |
9)Example:public abstract class Shape{public abstract void draw();} | Example:public interface Drawable{void draw();} |
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).
Q. What is ClassLoader?
Answer: The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. The Java run time system does not need to know about files and file systems because of classloaders.
Java classes aren’t loaded into memory all at once, but when required by an application. At this point, the Java ClassLoader is called by the JRE and these ClassLoaders load classes into memory dynamically.
A Java Classloader is of three types:
- BootStrap ClassLoader: A Bootstrap Classloader is a Machine code which kickstarts the operation when the JVM calls it. It is not a java class. Its job is to load the first pure Java ClassLoader. Bootstrap ClassLoader loads classes from the location rt.jar. Bootstrap ClassLoader doesn’t have any parent ClassLoaders. It is also called as the Primodial ClassLoader.
- Extension ClassLoader: The Extension ClassLoader is a child of Bootstrap ClassLoader and loads the extensions of core java classes from the respective JDK Extension library. It loads files from jre/lib/ext directory or any other directory pointed by the system property java.ext.dirs.
- System ClassLoader: An Application ClassLoader is also known as a System ClassLoader. It loads the Application type classes found in the environment variable CLASSPATH, -classpath or -cp command line option. The Application ClassLoader is a child class of Extension ClassLoader.
Note: The ClassLoader Delegation Hierarchy Model always functions in the order Application ClassLoader->Extension ClassLoader->Bootstrap ClassLoader. The Bootstrap ClassLoader is always given the higher priority, next is Extension ClassLoader and then Application ClassLoader.