1. What is garbage collection in Java?

Garbage collection is the process of automatically freeing memory on the heap by deleting objects that are no longer reachable in your program.

2. How does garbage collection work in Java?

Java’s garbage collector works by identifying objects that are no longer being used by a program, and reclaiming the memory allocated to them for reuse.

3. What are the benefits of garbage collection in Java?

It helps in automatically managing memory, preventing memory leaks, and improving application performance by reclaiming unused memory.

4. What is the Generational Garbage Collection in Java?

Generational Garbage Collection divides the heap into generations: young generation, old or tenured generation, and the permanent generation, optimizing garbage collection by focusing on areas with a higher likelihood of containing many unreachable objects.

5. Can we force garbage collection in Java?

While System.gc() suggests that the JVM performs garbage collection, it doesn’t guarantee it. Garbage collection cannot be forced.

6. What is the Mark and Sweep algorithm in garbage collection?

The Mark and Sweep algorithm is a two-phase process: the mark phase identifies unused objects, while the sweep phase reclaims memory used by these objects.

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

  • Strong Reference: The default type of reference, which prevents the referred object from being garbage-collected.
  • Soft Reference: These objects are cleared at the discretion of the garbage collector in response to memory demand.
  • Weak Reference: Weakly referenced objects do not prevent their referents from being made finalizable, finalized, and then reclaimed.
  • Phantom Reference: Objects that are being referenced are eligible for finalization but haven’t been finalized yet.

8. What triggers garbage collection in Java?

Garbage collection is typically triggered when the JVM runs out of free memory in the heap or when the System.gc() method is invoked.

9. What is the finalize() method in Java?

The finalize() method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

10. What is the difference between final, finally, and finalize in Java?

  • final: A keyword that can be applied to variables, methods, and classes indicating that they can’t be modified (variables), overridden (methods), or subclassed (classes).
  • finally: A block that follows a try block or a try-catch block that gets executed irrespective of an exception being thrown or not.
  • finalize: A method used by the garbage collector to perform cleanup actions before the object is garbage collected.

11. How do you monitor the garbage collection in Java?

Tools like VisualVM, JConsole, and command-line options like -verbose:gc can be used to monitor garbage collection in Java applications.

12. What are the types of garbage collectors in Java?

Major garbage collectors in Java include the Serial GC, Parallel GC, CMS (Concurrent Mark Sweep) GC, G1 GC, and ZGC (as of Java updates till my last training in April 2023).

13. What is the G1 garbage collector?

The G1 (Garbage-First) collector is a server-style garbage collector, aimed at multi-processor machines with large memories, that improves garbage collection pause times without sacrificing throughput.

14. How does the CMS garbage collector work?

The CMS (Concurrent Mark-Sweep) collector aims to minimize the pauses by doing most of the garbage collection work concurrently with the application threads.

15. What are some common garbage collection tuning parameters?

Common parameters include setting initial and maximum heap size (-Xms and -Xmx), selecting the garbage collector (-XX:+UseG1GC, -XX:+UseParallelGC), and setting the size of the young generation (-Xmn).

16. What is a memory leak in Java?

A memory leak in Java is a situation where objects are not garbage collected because they are still referenced by some part of the application, leading to unnecessary memory consumption and potential OutOfMemoryError.

17. What is the role of the Eden space in garbage collection?

The Eden space is part of the young generation where most objects are allocated. Objects that survive garbage collection cycles in the Eden space are moved to the survivor spaces and eventually to the old generation if they remain alive.

18. What is Stop-The-World (STW) event in garbage collection?

A Stop-The-World event is a pause during which the JVM stops all application threads to carry out garbage collection tasks.

19. How can we minimize garbage collection pauses in a Java application?

Tuning the garbage collector, optimizing application memory usage, and selecting appropriate JVM options can help minimize pauses due to garbage collection.

20. What is object reachability analysis in garbage collection?

Object reachability analysis is the process of determining whic

21. What is the difference between minor and major garbage collection in Java?

Minor garbage collection refers to the process of cleaning up the young generation, where most newly created objects reside and are quickly collected. Major garbage collection, on the other hand, deals with cleaning the old generation, which stores objects that have lived longer and is usually more expensive in terms of time.

22. What is a safe point in Java, and how is it related to garbage collection?

A safe point is a state in a program’s execution where all memory allocations are known and no Java bytecode instructions are being executed. Garbage collection typically occurs at these safe points to ensure that the application threads do not modify objects while they are being moved or marked for collection.

23. How does the Parallel Garbage Collector work, and when is it best used?

The Parallel Garbage Collector uses multiple threads to perform the young generation (minor) garbage collection, aiming to minimize pause times by leveraging multiple processors. It is best used in applications with a lot of spare CPU resources where pause times need to be minimized, such as in server environments.

24. Explain the concept of ‘promotion’ in garbage collection.

Promotion in garbage collection refers to the process of moving objects from the young generation to the old generation after they have survived a certain number of garbage collection cycles in the young generation. This process is necessary because it is assumed that if an object has lived long enough, it will likely continue to be used and should be allocated in an area of the heap that is collected less often.

25. What is the purpose of the Permanent Generation (PermGen) space, and how has it changed in recent Java versions?

The Permanent Generation (PermGen) space was used in earlier versions of Java to store class metadata and static fields. In Java 8 and later, the PermGen space was removed and replaced by the Metaspace, which grows automatically by default, thus reducing the chance of a PermGen space OutOfMemoryError.

26. How can developers minimize the impact of garbage collection on application performance?

Developers can minimize the impact by optimizing code to reduce unnecessary object creation, choosing the appropriate garbage collector for their application’s needs, tuning garbage collection parameters to optimize for throughput or pause times, and using memory efficiently to reduce the frequency and duration of garbage collection events.

27. What is String interning, and how does it affect garbage collection?

String interning is a method of storing only one copy of each distinct string value, which must be immutable. By interning strings, Java applications can significantly reduce the amount of memory used by duplicate strings, thus potentially decreasing the load on the garbage collector.

28. How does the Z Garbage Collector (ZGC) aim to improve garbage collection in Java?

The Z Garbage Collector (ZGC) is a scalable low-latency garbage collector introduced in later versions of Java to target applications requiring large heaps with minimal pause times. ZGC aims to improve garbage collection by using a region-based heap, colored pointers, and load barriers, among other techniques, to achieve pause times not exceeding 10ms.

29. What is garbage collection logging, and how can it be enabled in Java?

Garbage collection logging is a feature that allows developers to get detailed information about the garbage collection process, including the frequency of collection events, the amount of memory freed, and the time taken for each collection. It can be enabled using JVM flags such as -verbose:gc, -Xloggc:<file>, or -XX:+PrintGCDetails, depending on the Java version.

30. Describe the impact of reference objects (SoftReference, WeakReference, PhantomReference) on garbage collection.

Reference objects allow Java applications to maintain references to objects in a way that does not prevent their garbage collection. SoftReferences are cleared at the discretion of the garbage collector based on memory demand, WeakReferences are cleared when the garbage collector detects no strong references to the object, and PhantomReferences are used to schedule post-mortem cleanup actions. Proper use of these references can help manage memory more efficiently by allowing for the collection of objects that are not strictly needed, thereby reducing the risk of memory leaks.