Top 30 JVM (Java Virtual Machine) Interview Questions and Answers Question 1. What Is JVM in Java?

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Top 30 JVM(Java Virtual Machine) interview Questions and answers

Question 1. What is JVM in java?


It is very basic question to start your JVM interview.
JVM stands for Java virtual machine

JVM is the virtual machine on which java code executes.


JVM is responsible for converting byte code into machine specific code.

Question 2. Discuss HotSpot JVM (Java Virtual Machine) Architecture in short?


Freshers must prepare properly for this interview question.

HotSpot JVM (Java Virtual Machine) Architecture

JVM (Java Virtual Machine) consists of Class Loader Subsystem, Runtime Data
Areas and Execution Engine. Let’s discuss each of them in quickly.

1) Class Loader Subsystem of JVM    


Class loader is used to load class files.
2) Runtime Data Areas of JVM
2.1) Method Area > Method area stores data for each and every class like
fields,constant pool,method’s data and information
2.2) Heap > Heap is place where all objects are stored in JVM
2.3) Java Threads (Java thread Stacks) >Whenever new method is called new
stack frame is created and it is pushed on top of that thread's stack
2.4) Program counter registers (PC Registers) > the address of instructions
currently and next address being executed.
2.5) Native internal Threads (Native thread stack ) : Native internal threads area
contains all the informations related to native platform.

3) Execution Engine of JVM


3.1) JIT(Just In Time) compiler > JIT compiler compiles bytecodes to
machine code at run time and improves the performance of Java applications.
3.2) Garbage Collector - Garbage Collector Garbage collection is the proces
s by which JVM clears objects (unused objects) from heap to reclaim heap
space.

 Native method libraries of JVM > Native method interface is an


interface that connects JVM with the native method libraries for executing native
methods.

 JNI, What is Java Native Interface(JNI)?


 Programmers uses the JNI (Java Native Interface) to write the Java
native methods when an application cannot be written purely in Java.
 Read more about JNI(Java Native Interface)

Question 3. What is Class Loader Subsystem of JVM? What is its functioning and
purpose?
Answer.  It is important jvm interview question for experienced developers.

Classloader is a subsystem of JVM.


Classloader is used to load class files.
Classloader verifies the class file using byte code verifier. Class file will only be
loaded if it is valid.

Question 4. What are Runtime Data Areas of JVM? Discuss in detail?


Answer.   It is another important jvm interview question for experienced developers.
There are following Runtime Data Areas in JVM >
1) Method Area >
Method area is also called class area.
Method area stores data for each and every class like fields,constant pool,method’s
data and information.

2) Heap >
Heap is place where all objects are stored in JVM (java virtual machine).
Heap even contains arrays because arrays are objects.

3) Java Threads (Java thread Stacks) >


You must know that each and every thread has its own stack.

How stack frames are created when thread calls new method?
As we know each and every thread has its own stack. Whenever new method is
called new stack frame is created and it is pushed on top of that thread's stack.
What does thread stack contains?
The stack contain
 All the local variables,
 All the parameters,
 All the return address.
Does stack stores/contains object OR what stack doesn’t contains?
Stack never stores object, but it stores object reference.

4) Program counter registers (PC Registers) >


Program counter registers contains >
 the address of instructions currently being executed and
 address of next instruction as well.

5) Native internal Threads (Native thread stack ) >


Native internal threads area contains all the informations related to native platform.
Example - If we are running JVM (java application) on windows, it will contain all
information related to native platform i.e. windows.
If we are running JVM (java application) on linux, it will contain all information related
to native platform i.e. linux.

Question 5. What is Execution Engine of JVM?


Answer.   Another important jvm interview question for experienced developers.
Execution Engine contains JIT (Just In Time) Compiler and Garbage collector
compiler. Execution Engine also contains Interpreter.

1) JIT(Just In Time) compiler >


JIT compiler compiles bytecodes to machine code at run time and improves the
performance of Java applications.
JIT Compiler internal working >
JIT compilation does require processor time and memory usage. When the JVM first
starts up, lots of methods are called. Compiling all of these methods might can affect
startup time significantly, though program ultimately may achieve good performance.
Methods are not compiled when they are called first time. For each and every
method JVM maintains a call count, which is incremented every time the method is
called. The methods are interpreted by JVM until call count not exceeds JIT
compilation threshold (The JIT compilation threshold improves performance and
helps the JVM to start quickly. The threshold has been selected carefully by java
developers to obtain an optimal performances. Balance between startup times and
long term performance is maintained).
Therefore, very frequently used methods are compiled as soon as JVM has started,
and less used methods are compiled later.
2) Garbage Collector
Garbage Collector Garbage collection is the process by which JVM clears objects
(unused objects) from heap to reclaim heap space.

Garbage collection is the process of


 Identifying objects which are in use in java heap memory and
 Which objects are not in use in java heap memory and
 deleting the unused objects in java heap memory.

Interpreter > Interpreter is responsible for reading the bytecode and then executing
the instructions.

Question 6. What are most important/key HotSpot JVM components related to


performance?
Answer.  It is very important jvm interview question for experienced (5 years+)
developers and software architects.

Most important/key HotSpot JVM components related to performance are >


 Heap,
 JIT (Just In Time) Compiler and
 Garbage collector

Diagram : key components of HotSpot JVM (Java Virtual Machine) for


performance.
Three components Heap, JIT (Just In Time) Compiler and Garbage collector are
related to JVM’s performance tuning.

Heap and Garbage collector for tuning JVM’s performance >


All the objects are stored in heap. Garbage collector manages the heap at JVM
initialization.
There are many VM (JVM) options for
 Increasing and decreasing the heap size for managing object for best
performance.
 selecting the different garbage collector depending on your requirement.
JIT (Just In Time) Compiler for tuning JVM’s performance >
 JIT compiler compiles bytecodes to machine code at run time and improves
the performance of Java applications.
 In newer versions of JVM tuning of JIT (Just In Time) Compiler is rarely
needed.

The most important/key HotSpot JVM  components related to performance are


(IN SHORT) >
 Heap,
 JIT (Just In Time) Compiler and
 Garbage collector
 Heap and Garbage collector for tuning JVM’s performance > All the
objects are stored in heap. Garbage collector manages the heap at JVM
initialization.
 JIT (Just In Time) Compiler for tuning JVM’s performance > JIT
compiler compiles bytecodes to machine code at run time and improves the
performance of Java applications.

Question 7. What is JIT Compiler (Just In Time Compiler)? Explain in detail with
example.
Answer.  Most the developers know about JIT in short. So, it's become very difficult
and challenging to answer this jvm interview question. 5 years+ experienced
developers must prepare it well.

JIT compiler is a part of the JVM.

JIT compiles bytecodes to machine code at run time and improves the performance

of Java applications.

JIT Compiler internal working >


JIT compilation does require processor time and memory usage. When the JVM first

starts up, lots of methods are called. Compiling all of these methods might can affect

startup time significantly, though program ultimately may achieve good performance.

Methods are not compiled when they are called first time. For each and every

method JVM maintains a call count, which is incremented every time the method is

called. The methods are interpreted by JVM until call count not exceeds JIT

compilation threshold (The JIT compilation threshold improves performance and

helps the JVM to start quickly. The threshold has been selected carefully by java

developers to obtain an optimal performances. Balance between startup times and

long term performance is maintained).

Therefore, very frequently used methods are compiled as soon as JVM has started,

and less used methods are compiled later.

How JIT improves performance of Most frequently used methods ?

After a method is compiled, its call count is reset to zero and subsequent calls to the

method increment it call count. When the call count of a method reaches a JIT

recompilation threshold, the JIT compiler compiles method second time, applying

more optimizations as compared to optimizations applied in previous compilation.

This process is repeated until the maximum optimization level is reached. Most

frequently used methods are always optimized to maximize the performance benefits

of using the JIT compiler.

Example -

Let’s say JIT recompilation threshold = 2


After a method is compiled, its call count is reset to zero and subsequent calls to the

method increment it call count. When the call count of a method reaches a 2 (i.e. JIT

recompilation threshold), the JIT compiler compiles method second time, applying

more optimizations as compared to optimizations applied in previous compilation.

Disabling JIT compiler >

The JIT compiler can also be disabled, if disabled the entire Java program will be

interpreted. Disabling the JIT compiler is not recommended. We must disable JIT to

diagnose JIT compilation problems only.

For more details : What is JIT Compiler (Just In Time Compiler) in JVM

Question 8. What’s role of JVM in making java a platform independent language?


Answer. Another very important jvm interview question for all developers.
Once source code (i.e. .java file) is compiled on one platform(bytecode is formed).
That bytecode can be executed (interpreted) on any other platform running a JVM.
Every platform have different JVM implementation.
Example -
JVM for windows platform is different from JVM for linux platform.

Diagram to show java is platform independent>


The JVM is an very powerful and flexible runtime platform for languages  such as
Java, Groovy, Scala and Clojure. JVM provides large number of libraries and is
completely interoperable with Java.

Question 9. Is JVM available in JDK?


Answer.  It is very simple jvm interview question.
YES.
JDK = JRE + JVM.

Read : JVM (java virtual machine) in detail in java  and How Garbage Collection
(GC) works internally
Top 50 Garbage collection interview Questions and answers for experienced and
freshers

Question 10. Is JVM available in JRE?


Answer.  YES.
JRE = JVM + class libraries (rt.jar)  + other libraries (if any).
Question 11. What is Differences between JDK, JRE and JVM?
Answer.  It is important and simple jvm interview question. You must know about all
of these in detail, don’t confuse between these terms.

1) JDK (Java Development Kit)

As the name suggests, JDK is required for java development.

You need to have JDK in your system for >

 developing,

 compiling and

 running Java programs.

In short  JDK = JRE + JVM.

JDK diagram >


2) JRE (Java Runtime environment)

JRE provides environment for running/executing programs.

You need to have JRE in your system for >

 running Java programs.

JRE contains-

 JVM,

 class libraries (rt.jar)  and


 other supporting libraries (external jars, Ex - ojdbc.jar for JDBC) for executing

java program.

In short  JRE = JVM + class libraries (rt.jar)  + other libraries (if any).

JRE diagram >

Differences between JDK, JRE and JVM  


JDK JRE JVM

Java Development Kit Java Runtime environment java virtual machine

JDK is required for JRE provides environment JVM is the virtual machine

java development. for running/executing on which java code

programs. executes.

JVM is responsible for

converting byte code into

machine specific code.


We need JDK in your You need to have JRE in -

system for> your system for >

 developing,  running Java

 compiling and programs.

 running Java

programs. JRE contains-

 JVM,
JDK contains-
 class libraries and

 JRE and  other supporting

 JVM libraries.

In short   In short

JDK = JRE + JVM JRE = JVM + class libraries

(rt.jar)  + other libraries (if

any).

For detail please read -  JDK (Java Development Kit), JRE (Java Runtime
environment), JVM (java virtual machine), Differences between JDK, JRE and
JVM

Question 12. Mention some of the most important VM (JVM) PARAMETERS you
have used in JVM Heap memory?
Answer.  It is very very important garbage collection interview question for fresher
and experienced developer.

-Xms : Xms is minimum heap size which is allocated at initialization of JVM.


Examples of using -Xms VM (JVM) option in java >
java -Xms512m MyJavaProgram
It will set the minimum heap size of JVM to 512 megabytes.

-Xmx : Xmx is the maximum heap size that JVM can use.
Example of using -Xmx VM option in java >
java -Xmx512m MyJavaProgram
It will set the maximum heap size of JVM to 512 megabytes.

For more explanation -Xms and -Xmx JVM parameters and differences

-XX:NewRatio : NewRatio controls the size of young generation.


Example of using -XX:NewRatio  VM option in java >
-XX:NewRatio=3 means that the ratio between the young and old/tenured
generation is 1:3.

-XX:NewSize - NewSize is minimum size of young generation which is allocated


at initialization of JVM.

-XX:MaxNewSize - MaxNewSize is the maximum size of young generation that


JVM can use.

-XX:SurvivorRatio :   (for survivor space)


SurvivorRatio can be used to tune the size of the survivor spaces, but this is often
not as important for performance.

-XX:PermSize: It’s is initial value of Permanent Space which is allocated at startup


of JVM.
-XX:MaxPermSize: It’s maximum value of Permanent Space that JVM can allot up
to.

For explanation and example - What are -XX:PermSize and -XX:MaxPermSize with
Differences

Question 13. Mention some of the most important VM (JVM) PARAMETERS you
have used for Young Generation in JVM Heap memory?
Answer.  It is important garbage collection interview question for experienced
developers to specifically identify and answer jvm parameters for young generation.

-Xmn : -Xmn sets the size of young generation.


Example of using -Xmn VM (JVM) option in java >
java -Xmn512m MyJavaProgram
For more explanation and example - Read :  -Xmn JVM parameters
-XX:NewRatio : NewRatio controls the size of young generation.
Example of using -XX:NewRatio  VM option in java >
-XX:NewRatio=3 means that the ratio between the young and old/tenured
generation is 1:3.

-XX:NewSize - NewSize is minimum size of young generation which is allocated


at initialization of JVM.

-XX:MaxNewSize - MaxNewSize is the maximum size of young generation that


JVM can use.

-XX:SurvivorRatio :   (for survivor space)


SurvivorRatio can be used to tune the size of the survivor spaces, but this is often
not as important for performance.
Example of using -XX:SurvivorRatio > -XX:SurvivorRatio=6 sets the ratio
between each survivor space and eden to be 1:6.

Question 14. Mention some of the most important VM (JVM) PARAMETERS you
have used for Old Generation (tenured) in JVM Heap memory?
Answer.   It is difficult garbage collection interview question for experienced
developers to specifically identify and answer jvm parameters for old generation.

-XX:NewRatio : NewRatio controls the size of young and old generation.


Example of using -XX:NewRatio, -XX:NewRatio=3 means that the ratio between
the young and old/tenured generation is 1:3.
For more explanation and example -XX:NewRatio JVM parameters

Question 15. Mention some of the most important VM (JVM) PARAMETERS you
have used for Permanent Generation?
Answer.  Another complex and challenging garbage collection interview question for
experienced developers to specifically identify and answer jvm parameters for
permanent generation.

-XX:PermSize: It’s is initial value of Permanent Space which is allocated at startup


of JVM.
Example of using -XX:PermSize VM (JVM) option in java >
java -XX:PermSize=512m MyJavaProgram
It will set initial value of Permanent Space as 512 megabytes to JVM

-XX:MaxPermSize: It’s maximum value of Permanent Space that JVM can allot up
to.
Example of using -XX:MaxPermSize VM (JVM) option in java >
java -XX:MaxPermSize=512m MyJavaProgram
It will set maximum value of Permanent Space as 512 megabytes to JVM

For more details - What are -XX:PermSize and -XX:MaxPermSize with Differences

Read : JVM (java virtual machine) in detail in java  and How Garbage Collection
(GC) works internally

Question 16. What are -XX:MinHeapFreeRatio and -XX:MaxHeapFreeRatio vm


parameters used for?
Answer.  Though you hardly need to configure these parameters but you must know
about them.

-XX:MinHeapFreeRatio and -XX:MaxHeapFreeRatio


JVM can grows or shrinks the heap to keep the proportion of free space to live
objects within a specific range.

Question 17. What is significance of -XX:+AggressiveHeap VM parameter in java?


Answer. jvm interview question only for experienced software professionals.
-XX:+AggressiveHeap is used for Garbage Collection Tuning setting.
This VM option inspects the server resources and attempts to set various
parameters in optimal manner for for long running and memory consuming
applications. There must be minimum of 256MB of physical memory on the servers
before the AggressiveHeap can be used.

For more explanation and example - Read : -XX:+AggressiveHeap VM parameters

Question 18. Mention how to use different garbage collectors by passing vm


parameters in java?
Answer.  It is very important to know how to use different garbage collectors by
passing vm parameters.

1) Vm (JVM) option for enabling serial GC (garbage Collector) in java >


-XX:+UseSerialGC
Example of Passing Serial GC in Command Line for starting jar>
java -Xms256m -Xms512m  -XX:+UseSerialGC -jar d:\MyJar.jar

2) Vm (JVM) option for enabling throughput GC (Garbage collector) in java >


-XX:+UseParallelGC

Or  (throughput collector with n number of threads)


-XX:ParallelGCThreads=<numberOfThreads>
Or
-XX:+UseParallelOldGC
3) Vm (JVM) option for enabling Concurrent Mark Sweep (CMS) Collector in java >
-XX:+UseConcMarkSweepGC

Or  (CMS garbage collector with n number of threads)


-XX:ParallelCMSThreads=<n>

4) Vm (JVM) option for enabling G1 Garbage Collector


-XX:+UseG1GC

Question 19. How to Solve OutOfMemoryError : unable to create new native


Thread by passing appropriate jvm parameter?
Answer.  A
You can resolve “java.lang.OutOfMemoryError : unable to create new native
Thread” by setting the appropriate size using -Xss vm option.

Solution 1 to “java.lang.OutOfMemoryError : unable to create new native


Thread”  >
Try to increase the the -Xss value so that new threads gets enough stack space.

Solution 2 to “java.lang.OutOfMemoryError : unable to create new native


Thread”  >
Alternatively you could also increase the heap size available using -Xms and -Xmx
options and then try to increase and set appropriate -Xss value.

Example of using -Xss


Pass memory value you want to allocate to thread stack with -Xss.
java -Xss512m MyJavaProgram
It will set the default stack size of JVM  to 512 megabytes.

Question 20. How to Solve OutOfMemoryError : Java heap space by passing


appropriate jvm parameter?
Answer.  A
OutOfMemoryError : Java heap space - is thrown whenever there is insufficient
space to allocate an object in the Java heap.

Does Exception in thread threadName - java.lang.OutOfMemoryError - Java


heap space indicates memory leak?
No, this OutOfMemoryError does not necessarily means that it is memory leak.

Increase the heap size using -Xms and -Xmx jvm parameters as a solution to this
issue.
Must read: How to set, change, increase or decrease heap size in tomcat server
and eclipse to avoid OutOfMemoryError ?

>How to set or change permgen size in tomcat server, eclipse?

Read : JVM (java virtual machine) in detail in java  and How Garbage Collection
(GC) works internally
Top 50 Garbage collection interview Questions and answers for experienced and
freshers

Question 21. Discuss about Error occurred during initialization of VM : caused


because of heap space problem?
Answer.  A

>Error occurred during initialization of VM - Unable to allocate KB card tables for


parallel garbage collection for the requested KB heap. Error: Could not create
the Java Virtual Machine

>Too small initial heap


>Could not reserve enough space for object heap
>Error occurred during initialization of VM - Initial heap size set to a larger value
than the maximum heap size

>There is insufficient memory for the Java Runtime Environment to continue.


Native memory allocation (malloc) failed to allocate 1048576 bytes for
AllocateHeap
Set appropriate values of xmx and xms to avoid - Error occurred during
initialization of VM.

Question 22. How to set appropriate heap size in eclipse in java?


Answer.  We can make changes in eclipse.ini file.
Where we can configure
 -Xms (minimum heap size which is allocated at initialization of JVM),
 -Xmx (maximum heap size that JVM can use. )

 -XX:MaxPermSize: It’s maximum value of Permanent Space that JVM can


allot up to.

Question 23. How to pass VM parameter to java program through CMD?


Answer.  Please read How to write java program to pass VM/JVM parameters
through CMD

Question 24. How to pass VM parameter to java program in eclipse?


Answer.  Please read How to pass vmArgs(JVM parameters) to java program in
eclipse
Question 25. How to pass VM parameter to tomcat in eclipse?
Answer.  Please read How to pass VM argument to tomcat in eclipse
Earlier we learned How to set or change permgen size in tomcat server, eclipse
And How to set, change, increase or decrease heap size in tomcat server to avoid
OutOfMemoryError ?

Read : JVM (java virtual machine) in detail in java  and How Garbage Collection
(GC) works internally

Now, let’s prepare few JVM related java programs for interview >

Question 26. Find out total number of available processors to JVM?


Answer.  We will use availableProcessors() method.

Example/program to Find out total Number Of Processors Available to  JVM

(Java virtual machine) In your System in java >

public class FindNumberOfAvailableProcessorsInSystemExample{


   public static void main(String[] args) {
         
     /**
     * first we will get the java Runtime object using the
     * Runtime class's getRuntime() method in java.
     */
       Runtime runtime = Runtime.getRuntime();
     
     /**
     * Now,  Find out total Number Of Processors Available to
     * JVM (Java virtual machine) In System
     * We will use native method availableProcessors in java.
     */
    
     int numberOfProcessors = runtime.availableProcessors();
    
     System.out.println("total Number Of Processors Available to "
             + "JVM (Java virtual machine) In your System = "+numberOfProcessors);
   }
}
/* output
total Number Of Processors Available to JVM (Java virtual machine) In your
System = 4
*/
Question 27. Find Total Amount Of Memory In JVM?
Answer.  We will use totalMemory() method.

About totalMemory() method of java.lang.Runtime class in java >


 totalMemory() method of Runtime class returns the total amount of memory in
the JVM (Java virtual machine).
 totalMemory() is the native method in java, so value returned by this method
depends on the host environment.

Example/program to Find Total Amount Of Memory In

JVM (Java virtual machine) In your System >

public class TotalAmountOfMemoryInJavaVirtualMachineExample{


   public static void main(String[] args) {
         
     /**
     * first we will get the java Runtime object using the
     * Runtime class's getRuntime() method in java.
     */
       Runtime runtime = Runtime.getRuntime();
     
     /**
     * totalMemory() method of Runtime class returns the total
     * amount of memory in the JVM (Java virtual machine).
     * totalMemory() is the native method, so value returned by this
     * method depends on the host environment.
     */
    
     long totalMemoryInJVM = runtime.totalMemory();
      
       System.out.println("Total amount of memory in the "
             + "JVM (Java virtual machine) in bytes = "+ totalMemoryInJVM);
   }
}
/* output
Total amount of memory in the JVM (Java virtual machine) in bytes =
257425408
*/

Question 28. Find Free Memory Available In Java virtual machine?


Answer.  We will use freeMemory() method.
About freeMemory() method of java.lang.Runtime class in java >
 freeMemory() method of Runtime class returns the total amount of free
memory in the JVM (Java virtual machine).
 freeMemory() is the native method in java.

Also read about : How garbage collection works internally in java

Example/program to Find Free Memory Available In JVM (Java virtual machine)

In your System >

/**
* Example/program to Find Free Memory Available In
* JVM (Java virtual machine) In your System
*/
public class FreeMemoryAvailableInJavaVirtualMachineExample{
   public static void main(String[] args) {
         
     /**
     * first we will get the java Runtime object using the
     * Runtime class's getRuntime() method in java.
     */
       Runtime runtime = Runtime.getRuntime();
     
     /**
     * freeMemory() method of Runtime class returns the total
     * amount of free memory in the JVM (Java virtual machine).
     *
     * freeMemory() is the native method.
     *
     * Calling gc (garabage collector) may result in
     * increasing free memory in java.
     */
    
       long freeMemoryAvailableInJVM = runtime.freeMemory();
      
       System.out.println("Total amount of free memory available in the "
             + "JVM (Java virtual machine) in bytes = "+ freeMemoryAvailableInJVM);
   }
}
/* output
Total amount of free memory available in the JVM (Java virtual machine) in bytes
= 253398664
*/

Question 29. Find Maximum Memory That JVM can use?


Answer.  We will use maxMemory() method.
About maxMemory() method of java.lang.Runtime class in java >
 maxMemory() method of Runtime class returns maximum amount of memory
that the JVM (Java virtual machine) will try to use.
 maxMemory() is the native method in java.

Example/program to Find Maximum Memory That

JVM (Java virtual machine) Attempts To Use >

/**
* Example/program to Find Maximum Memory That
* JVM (Java virtual machine) AttemptsToUseExample
*/
public class FindMaximumMemoryThatJVMAttemptsToUseExample{
   public static void main(String[] args) {
         
     /**
     * first we will get the java Runtime object using the
     * Runtime class's getRuntime() method in java.
     */
       Runtime runtime = Runtime.getRuntime();
     
     /**
     * maxMemory() method of Runtime class returns maximum amount
     * of memory that the JVM (Java virtual machine) will try to use
     *
     * maxMemory() is the native method.
     *
     */
    
       long maximumMemoryThatJVMAttemptsToUse = runtime.maxMemory();
      
       System.out.println("Maximum Memory That "
                 + "JVM (Java virtual machine) will try to use "
             + "in bytes = "+ maximumMemoryThatJVMAttemptsToUse);
   }
}
/* output
Maximum Memory That JVM (Java virtual machine) will try to use in bytes =
3797417984
*/

Question 30. How to terminate JVM in java?


Answer.  It is important jvm interview question.
We can terminate JVM using halt() and exit() method. Let’s see both the ways and
difference between them. It's becomes complex and challenging jvm interview
question when you need to answer the difference between two methods with
program.
1) Terminate JVM (Java virtual machine) using halt method in java >

About halt() method of java.lang.Runtime class in java >


 halt() method of Runtime class
 halt method terminates the running JVM (Java virtual machine) forcibly.
 halt method never returns normally in java.
 Two important points about halt method in java >
 1) halt method does not allows even already registered ShutdownHook
to be executed (shown in program 2 below) in java And
 2) halt method even does not run the uninvoked finalizers if finalization-
on-exit has been enabled in java.

1.1) Example/program to terminate JVM (Java virtual machine) using halt

method in java >

/**
* Example/program to terminate
* JVM (Java virtual machine) using halt method
*/
public class TerminateJVMExampleUsingHaltMethod{
  public static void main(String[] args) {
  
      System.out.println("Halt method program - to terminate JVM (Java virtual
machine)");
         
     /**
     * first we will get the java Runtime object using the
     * Runtime class's getRuntime() method in java.
     */
      Runtime runtime = Runtime.getRuntime();
  
     /**
     * halt method of Runtime class
     * terminates the running JVM (Java virtual machine) forcibly.
     * halt method never returns normally.
     */
       runtime.halt(1); //pass status as 1
      
       System.out.println("JVM (Java virtual machine) halted"); //This line won't be
printed
  }
  
  
}
/* output
Halt method program - to terminate JVM (Java virtual machine)
*/

1.2) Program to terminate JVM (Java virtual machine) using halt method And

Show registered ShutdownHooks Are NOT Executed in java. Click here

/**
* Example/program to terminate
* JVM (Java virtual machine)
* Using Halt Method And Show registered
* ShutdownHooks Are Not Executed
*/
public class
TerminateJVMUsingHaltMethodAndShowShutdownHooksAreNotExecuted{
   public static void main(String[] args) {
        System.out.println("halt method program - to terminate JVM (Java virtual
machine)");
         
       Runtime runtime = Runtime.getRuntime();
  
       //Register/ add ShutdownHook, it won't get called after
       //JVM is shutDown using halt method.
       Runtime.getRuntime().addShutdownHook(new Thread(){
       public void run() {
                 System.out.println("Executing shutdown hook...");
         System.out.println("shutdown hook executed successfully");
       }
     });
      //call halt method
       runtime.halt(1);
      
       System.out.println("JVM (Java virtual machine) halted"); //This line won't be
printed
   }
  
  
}
/* output
halt method program - to terminate JVM (Java virtual machine)
*/

2) Terminate JVM (Java virtual machine) using exit method in java >

About exit() method of java.lang.Runtime class in java >

 exit method of Runtime class


 Exit method terminates the running JVM (Java virtual machine) by initiating
the shutdown sequence in java.
 exit method never returns normally in java.
 Two important phases of shutdown sequence initiated by exit method in java
>
 1) exit method does allows to run already registered ShutdownHook to
be executed (shown in program 4 below) And
 2) halt method runs the uninvoked finalizers if finalization-on-exit has
been enabled.

2.1) Example/program to terminate JVM (Java virtual machine) using exit

method in java >

/**
* Example/program to terminate
* JVM (Java virtual machine) using exit method  
*/
public class TerminateJVMExampleUsingExitMethod{
  public static void main(String[] args) {
  
       System.out.println("Exit method program - to terminate JVM (Java virtual
machine)");
         
      /**
     * first we will get the java Runtime object using the
     * Runtime class's getRuntime() method in java.
     */
      Runtime runtime = Runtime.getRuntime();
  
     /**
     * exit method of Runtime class
     * terminates the running JVM (Java virtual machine) by
     * initiating the shutdown sequence.
     *
     */
       runtime.exit(1); //pass status as 1 to exit method
      
       System.out.println("JVM (Java virtual machine) halted"); //This line won't be
printed
  }
  
  
}
/* output
Exit method program - to terminate JVM (Java virtual machine)
*/
2.2) Program to terminate JVM (Java virtual machine) using exit method And

Show registered ShutdownHooks Are Executed in java. Click here

/**
* Example/program to terminate
* JVM (Java virtual machine)
* Using exit Method And Show registered
* ShutdownHooks Are Executed
*/
public class
TerminateJVMUsingExitMethodAndShowShutdownHooksAreExecuted{
   public static void main(String[] args) {  
         
        System.out.println("Exit method program - to terminate JVM (Java virtual
machine)");
         
       Runtime runtime = Runtime.getRuntime();
  
       //Register/ add ShutdownHook, it will get called after
       //JVM is shutDown using exit method.
       Runtime.getRuntime().addShutdownHook(new Thread(){
       public void run() {
          try{
                System.out.println("Executing shutdown hook...");
          }catch (Exception e){
                e.printStackTrace();
          }
          System.out.println("shutdown hook executed successfully");
       }
     });
        //call exit method
       runtime.exit(1);
      
       System.out.println("JVM (Java virtual machine) exited"); //This line won't be
printed
   }
  
  
}
/* output
Exit method program - to terminate JVM (Java virtual machine)
Executing shutdown hook...
shutdown hook executed successfully
*/

You might also like