Top 12 Java Memory Management Interview Questions
Q1. What Is Generational Garbage Collection And What Makes It A Popular Garbage Collection Approach?
Generational rubbish collection may be loosely defined because the strategy utilized by the rubbish collector in which the heap is divided into some of sections called generations, every of so as to maintain objects consistent with their “age” at the heap.
Whenever the rubbish collector is jogging, step one inside the manner is known as marking. This is in which the garbage collector identifies which pieces of reminiscence are in use and which are not. This may be a very time-ingesting technique if all items in a machine ought to be scanned.
As increasingly more items are allocated, the listing of gadgets grows and grows leading to longer and longer rubbish series time. However, empirical analysis of programs has shown that most gadgets are brief-lived.
With generational garbage series, objects are grouped in keeping with their “age” in terms of how many rubbish series cycles they have survived. This manner, the majority of the work spread throughout various minor and principal series cycles.
Today, nearly all rubbish collectors are generational. This method is so famous due to the fact, over the years, it has demonstrated to be the best answer.
Q2. What Are Stack And Heap? What Is Stored In Each Of These Memory Structures, And How Are They Interrelated?
The stack is part of memory that incorporates facts approximately nested technique calls down to the present day function in the application. It also contains all neighborhood variables and references to items at the heap defined in currently executing strategies.
This shape permits the runtime to go back from the technique understanding the address whence it turned into called, and additionally clean all neighborhood variables after exiting the method. Every thread has its own stack.
The heap is a large bulk of reminiscence intended for allocation of items. When you create an item with the brand new key-word, it gets allotted on the heap. However, the reference to this object lives at the stack.
Q3. Describe In Detail How Generational Garbage Collection Works?
To well recognize how generational rubbish series works, it is important to first consider how Java heap is based to facilitate generational garbage series.
The heap is split up into smaller areas or generations. These areas are Young Generation, Old or Tenured Generation, and Permanent Generation.
The younger era hosts most of the newly created gadgets. An empirical take a look at of most applications shows that majority of objects are quickly brief lived and therefore, soon turn out to be eligible for series. Therefore, new objects start their journey here and are handiest “promoted” to the antique technology space when they have attained a positive “age”.
The time period “age” in generational rubbish collection refers to the range of series cycles the item has survived.
The younger generation area is further divided into three areas: an Eden area and survivor spaces which include Survivor 1 (s1) and Survivor 2 (s2).
The old era hosts gadgets that have lived in memory longer than a sure “age”. The gadgets that survived garbage series from the younger technology are promoted to this space. It is normally larger than the young generation. As it is larger in length, the garbage series is more high-priced and occurs less often than within the younger generation.
The permanent era or extra commonly referred to as, PermGen, incorporates metadata required by means of the JVM to describe the lessons and methods used inside the software. It also contains the string pool for storing interned strings. It is populated via the JVM at runtime based on classes in use through the utility. In addition, platform library classes and techniques may be stored here.
First, any new gadgets are allotted to the Eden space. Both survivor areas start off empty. When the Eden space fills up, a minor rubbish series is brought about. Referenced objects are moved to the primary survivor area. Unreferenced gadgets are deleted.
During the next minor GC, the same thing occurs to the Eden space. Unreferenced gadgets are deleted and referenced gadgets are moved to a survivor space. However, in this case, they're moved to the second one survivor area (S1).
In addition, objects from the final minor GC inside the first survivor space (S0) have their age incremented and are moved to S@Once all surviving objects have been moved to S1, each S0 and Eden area are cleared. At this point, S1 contains items with special a long time.
At the next minor GC, the equal system is repeated. However this time the survivor areas switch. Referenced items are moved to S0 from each Eden and S@Surviving objects are aged. Eden and S1 are cleared.
After each minor garbage series cycle, the age of each item is checked. Those which have reached a certain arbitrary age, as an example, 8, are promoted from the younger era to the vintage or tenured era. For all next minor GC cycles, gadgets will remain promoted to the vintage generation space.
This quite a lot exhausts the system of garbage collection within the younger technology. Eventually, a first-rate rubbish collection may be finished at the antique technology which cle up and compacts that space. For every important GC, there are numerous minor GCs.
Q4. What Is A Stringbuilder And What Are Its Use Cases? What Is The Difference Between Appending A String To A Stringbuilder And Concatenating Two Strings With A + Operator? How Does Stringbuilder Differ
StringBuilder lets in manipulating person sequences by means of appending, deleting and placing characters and strings. This is a mutable records structure, in preference to the String elegance which is immutable.
When concatenating String times, a new item is created, and strings are copied. This may want to bring a big garbage collector overhead if we need to create or alter a string in a loop. StringBuilder lets in dealing with string manipulations an awful lot more correctly.
StringBuffer is different from StringBuilder in that it is thread-safe. If you need to control a string in a unmarried thread, use StringBuilder as an alternative.
Q5. When Does An Object Become Eligible For Garbage Collection? Describe How The Gc Collects An Eligible Object?
An item becomes eligible for Garbage collection or GC if it isn't always available from any stay threads or with the aid of any static references.
The maximum straightforward case of an item becoming eligible for rubbish series is that if all its references are null. Cyclic dependencies with none stay external reference also are eligible for GC. So if object A references object B and object B references Object A and that they don’t have some other live reference then each Objects A and B will be eligible for Garbage series.
Another obvious case is when a figure object is about to null. When a kitchen object internally references a refrigerator item and a sink item, and the kitchen object is about to null, each refrigerator and sink will become eligible for garbage series alongside their parent, kitchen.
Q6. Are There Any Disadvantages Of Garbage Collection?
Yes. Whenever the garbage collector runs, it has an impact at the application’s performance. This is due to the fact all different threads inside the utility must be stopped to allow the garbage collector thread to efficiently do its paintings.
Depending at the necessities of the utility, this may be a real problem that is unacceptable by means of the purchaser. However, this trouble may be substantially reduced or maybe removed through skillful optimization and rubbish collector tuning and using special GC algorithms.
Q7. Describe Strong, Weak, Soft And Phantom References And Their Role In Garbage Collection?
Much as memory is controlled in Java, an engineer might also want to carry out as a great deal optimization as feasible to decrease latency and maximize throughput, in crucial programs. Much as it's miles not possible to explicitly control when garbage series is induced within the JVM, it is possible to influence how it occurs as regards the items we have created.
Java affords us with regard gadgets to control the connection among the items we create and the garbage collector.
By default, each object we create in a Java software is strongly referenced by using a variable:
StringBuilder sb = new StringBuilder();
In the above snippet, the new keyword creates a new StringBuilder object and stores it at the heap. The variable sb then shops a strong connection with this item. What this me for the rubbish collector is that the particular StringBuilder item isn't always eligible for collection in any respect due to a strong reference held to it via sb. The story simplest modifications while we nullify sb like this:
sb = null;
After calling the above line, the object will then be eligible for series.
We can trade this relationship among the item and the garbage collector by using explicitly wrapping it inside some other reference item which is located inner java.Lang.Ref bundle.
A smooth reference can be created to the above item like this:
StringBuilder sb = new StringBuilder();
SoftReference<StringBuilder> sbRef = new SoftReference<>(sb);
sb = null;
In the above snippet, we've got created two references to the StringBuilder object. The first line creates a sturdy reference sb and the second line creates a soft reference sbRef. The 1/3 line have to make the item eligible for series but the rubbish collector will put off collecting it due to sbRef.
The tale will best change whilst reminiscence will become tight and the JVM is getting ready to throwing an OutOfMemory blunders. In other words, gadgets with only tender references are amassed as a last lodge to get better memory.
A vulnerable reference may be created in a similar manner using Weak Reference magnificence. When sb is set to null and the StringBuilder item handiest has a vulnerable reference, the JVM’s garbage collector will have definitely no compromise and right now accumulate the object on the very next cycle.
A phantom reference is similar to a susceptible reference and an object with most effective phantom references could be collected with out ready. However, phantom references are enqueued as soon as their items are accumulated. We can poll the reference queue to recognize precisely when the item turned into accrued.
Q8. How Are Strings Represented In Memory?
A String instance in Java is an item with two fields: a char[] fee discipline and an int hash subject. The fee field is an array of chars representing the string itself, and the hash subject carries the hashCode of a string which is initialized with 0, calculated all through the first hashCode() call and cached ever when you consider that. As a curious facet case, if a hashCode of a string has a 0 cost, it needs to be recalculated whenever the hashCode() is referred to as.
Important aspect is that a String instance is immutable:
you can’t get or regulate the underlying char[] array. Another function of strings is that the static constant strings are loaded and cached in a string pool.
If you've got multiple identical String items in your source code, they're all represented through a single example at runtime.
Q9. What Happens When There Is Not Enough Heap Space To Accommodate Storage Of New Objects?
If there's no reminiscence area for growing a brand new item in Heap, Java Virtual Machine throws OutOfMemoryError or extra specially java.Lang.OutOfMemoryError heap area.
Q10. Suppose We Have A Circular Reference ( Objects That Reference Each Other). Could Such Pair Of Objects Become Eligible For Garbage Collection And Why?
Yes, a pair of items with a round reference can grow to be eligible for rubbish series. This is because of how Java’s rubbish collector handles round references. It considers gadgets stay no longer after they have any connection with them, however whilst they are reachable through navigating the item graph beginning from some rubbish collection root (a nearby variable of a live thread or a static area). If a couple of objects with a circular reference isn't always accessible from any root, it's far considered eligible for garbage series.
Q11. How Do You Trigger Garbage Collection From Java Code?
You, as Java programmer, can not pressure garbage collection in Java; it will handiest trigger if JVM thinks it wishes a garbage series primarily based on Java heap size.
Before disposing of an object from reminiscence rubbish series thread invokes finalize()technique of that object and gives an possibility to carry out any form of cleanup required. You can also invoke this approach of an object code, however, there's no guarantee that rubbish collection will arise whilst you name this technique.
Additionally, there are methods like System.Gc() and Runtime.Gc() that's used to ship request of Garbage collection to JVM however it’s now not guaranteed that rubbish series will show up.
Q12. What Is Garbage Collection And What Are Its Advantages?
Garbage collection is the technique of searching at heap memory, figuring out which gadgets are in use and which aren't, and deleting the unused gadgets.
An in-use object, or a referenced object, me that a few a part of your program nonetheless continues a pointer to that object. An unused item, or unreferenced object, is not referenced by any a part of your application. So the reminiscence used by an unreferenced item may be reclaimed.
The biggest benefit of rubbish series is that it gets rid of the load of guide memory allocation/deal vicinity from us so that we can awareness on fixing the hassle to hand.

