Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Which part of the memory is used in Garbage Collection?


Download 1.52 Mb.
Pdf ko'rish
bet72/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   68   69   70   71   72   73   74   75   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Which part of the memory is used in Garbage Collection?
Which algorithm does the JVM use for Garbage
collection?
Answer:
Garbage Collection is done in the heap memory. The JVM uses
the mark and sweep algorithm internally for garbage collection.
When does garbage collection occur?
Answer:
The JVM (Java Virtual Machine) controls the garbage collection
process. So, the JVM decides when the garbage collection
process should run.
It is also possible to explicitly request garbage collection through
Java code via the System.gc() or
Runtime.getRuntime().gc() method. However, there is no
guarantee that invoking these methods will run the garbage
collector.
What code needs to be written in order to trigger garbage
collection?
Answer:
Garbage collection can be triggered in one of the following ways:
Method 1– Using Runtime.gc() as follows:
Runtime runTime = Runtime.getRuntime();
runTime.gc();


196.
Method 2– Using System.gc() as follows:
System.gc();
Both these approaches do not guarantee garbage collection, it is
up–to the JVM to actually decide when to run the garbage
collector
Explain with a code sample how an object becomes
eligible for garbage collection.
Answer:
An object becomes eligible for garbage collection when it is no
longer referenced. The following scenarios demonstrate this:
Scenario 1– Setting the object to null
String stringValue = “This is a String value”; //Line 1
stringValue = null; //Makes stringValue
eligible for GC
Scenario 2– Re–assigning a variable
String str1 = “Hello”;
String str2 = str1; //makes str1 eligible for GC

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   68   69   70   71   72   73   74   75   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling