Prev Next

Java / Garbage collection

1. What is the purpose of garbage collection in Java? 2. How does Garbage Collection work in Java? 3. Explain the structure of heap. 4. Is garbage collection in Java automatic? 5. When does an Object become eligible for Garbage collection in Java? 6. How will you identify minor and major garbage collection in Java? 7. Difference between system.gc() and runtime.gc(). 8. How to identify if GC resulted due to calling System.gc()? 9. What is finalize method in Java? 10. How many times does the GC calls the finalize() method for an object? 11. What does System.gc() and Runtime.gc() methods do ? 12. If an object reference is set to null, will the GC immediately free the memory held by that object ? 13. How do you trigger garbage collection through Java code? 14. Does finalize method automatically chain like constructors? 15. How to improve the possibility of JVM running of finalize method? 16. Does Java support destructors? 17. When to override finalize method in Java? 18. What is the access modifier for finalize method? 19. Best practice for calling super class finalize method. 20. Can we call finalize method explicitly? 21. What to avoid when overriding finalize method? 22. What are the Garbage collection (GC) roots? 23. Explain Stop-The-World (STW) pauses. 24. What is JVM ergonomics? 25. What is the default garbage collector on a server class Machine. 26. What are the 2 JVM tuning parameters for parallel collector? 27. What is the default garbage collector in Java? 28. Explain Serial garbage collector. 29. How to find which Garbage collector is running? 30. Is objects with circular reference, object linked to each other, garbage collected? 31. Explain JVM Escape Analysis.
Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. What is the purpose of garbage collection in Java?

The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application so that the resources be reclaimed and reused.

2. How does Garbage Collection work in Java?

Garbage collection works by employing several GC algorithms, for example, Mark and Sweep.

Garbage Collector is the program running in the background that looks into all the objects in the memory and find out objects that are not referenced by any part of the program. All these unreferenced objects are deleted and space is reclaimed for allocation to other objects.

There are many kinds of garbage collector available in Java to collect different area of heap memory, some of them include serial, parallel and concurrent garbage collectors.

The basic way of garbage collection involves 3 steps:

  • Marking is the first step where garbage collector identifies which objects are in use and which ones are not in use.
  • Normal Deletion: Garbage Collector removes the unused objects and reclaim the free space to be allocated to other objects.
  • Deletion with Compacting: After deleting unused objects, all the survived objects can be moved to be together. This will increase the performance of allocation of memory to newer objects.
3. Explain the structure of heap.

Heap is divided into different generation, for example, new (young) generation, old generation and PermGen space.PermGen space is used to store class metadata and over filling of PermGen space can cause java.lang.OutOfMemoryError:PermGen space.

Young Generation : It is place where lived for short period and divided into 2 spaces:

  • Eden Space : When object created using new keyword memory allocated on this space.
  • Survivor Space : This is the pool which contains objects which have survived after java garbage collection from Eden space.

Old Generation : This pool is basically contain tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from Young Generation.

  • Tenured Space: This memory pool contains objects which survived after multiple garbage collection means object which survived after garbage collection from Survivor space.

Permanent Generation : This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.

In Java8, PermGen is replaced with Metaspace which is very similar. Main difference is that Metaspace re-sizes dynamically.

Code Cache (Virtual or reserved) : HotSpot Java VM includes code cache area that has memory which will be used for compilation and storage of native code.

4. Is garbage collection in Java automatic?

Yes, Java does automatic garbage collection, unlike other programming languages such as C where memory allocation and deallocation is a manual process.

5. When does an Object become eligible for Garbage collection in Java?

An object becomes eligible for garbage collection when there is no reference for that object or it inaccessible by any live thread.

Cyclic reference where two objects are pointing to each other and there is no live reference for any of them, than both are eligible for GC.

Garbage collection thread is a daemon thread which will run by JVM based upon GC algorithm and when runs it collects all objects which are eligible for GC.

6. How will you identify minor and major garbage collection in Java?

By enabling logging using -verbose:gc or -XX:PrintGCDetails it can be identified.

Minor collection prints GC if garbage collection logging is enabled, while Major collection prints Full GC.

7. Difference between system.gc() and runtime.gc().

There is no significant difference between System.gc() and Runtime.gc().

System.gc() internally calls Runtime.gc(). The only difference is System.gc() is a class method whereas Runtime.gc() is an instance method.

Runtime.gc() is a native method whereas System.gc() is non - native method which in turn calls the Runtime.gc().

Calling System.gc is more convenient than Runtime.gc as we call class method directly.

8. How to identify if GC resulted due to calling System.gc()?

If garbage collection logging is enabled using -verbose:gc, the word System will be printed when GC resulted by invoking System.gc method.

9. What is finalize method in Java?

The java.lang.Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to that object. A subclass overrides the finalize method to dispose the system resources or to perform other cleanup actions.

protected void finalize()

Finalize method is also called as finalizer .

This method throws Throwable exception. Exceptions occurred in finalize() method are not propagated and ignored by the garbage collector.

10. How many times does the GC calls the finalize() method for an object?

Just once.

11. What does System.gc() and Runtime.gc() methods do ?

By calling one of these methods, we can give a hint to the JVM, in order to start a garbage collection. However, it is up to the JVM to start the garbage collection immediately or later in time.

12. If an object reference is set to null, will the GC immediately free the memory held by that object ?

No, the object will be available for garbage collection only in the next cycle of the garbage collector.

13. How do you trigger garbage collection through Java code?

The methods System.gc() and Runtime.gc() may be used to send request of Garbage collection to JVM but it is not guaranteed that garbage collection will happen.

We can call finalize method manually however that also does not guarantee object be garbage colllected.

14. Does finalize method automatically chain like constructors?

No. It is developer responsibility to call finalize() method of the superclass, if not called explicitly, finalize of super class will never be called.

15. How to improve the possibility of JVM running of finalize method?

Call System.runFinalization() or Runtime.getRuntime().runFinalization() method.

Though not guaranteed, these methods increase possibility that JVM call finalize() method of all object which are eligible for garbage collection and whose finalize has not yet called.

16. Does Java support destructors?

No.

17. When to override finalize method in Java?

If a Java class hold resource like input-output streams such as File, JDBC connection then you should override finalize and call its close() method from finalize. Though not guaranteed, finalize method acts as the last attempt to release the resources.

18. What is the access modifier for finalize method?

The overriden finalize method can be either protected or public.

19. Best practice for calling super class finalize method.

Call superclass finalize method in the finally block. This will guarantee that finalize of the parent class will be called in all condition except when JVM exits.

20. Can we call finalize method explicitly?

We may not, it is not a normal method and to be called only by JVM garbage collection thread.

21. What to avoid when overriding finalize method?

Since finalize method execution is not guaranteed, use it only as the last attempt to resource not as first or only attempt.

22. What are the Garbage collection (GC) roots?
  • Local variable and input parameters of the currently executing methods.
  • Active threads.
  • Static field of the loaded classes.
  • and JNI references.
23. Explain Stop-The-World (STW) pauses.

Garbage collection can cause the JVM to pause all the application threads. Such pauses are called Stop-The-World (STW) pauses.

24. What is JVM ergonomics?

Ergonomics is the process by which the Java Virtual Machine (JVM) and garbage collection tuning, such as behavior-based tuning, improve application performance. The JVM provides platform-dependent default selections for the garbage collector, heap size, and runtime compiler. These selections match the needs of different types of applications while requiring less command-line tuning. In addition, behavior-based tuning dynamically tunes the sizes of the heap to meet a specified behavior of the application.

25. What is the default garbage collector on a server class Machine.

Throughput Garbage collector. Throughput GC is also known as parallel GC.

26. What are the 2 JVM tuning parameters for parallel collector?

Maximum Pause Time Goal is the duration during which the garbage collector stops the application and recovers space that is no longer in use. The intent of the maximum pause time goal is to limit the longest of these pauses.

The maximum pause time goal is specified with the command-line option -XX:MaxGCPauseMillis=<nnn>. This is interpreted as a hint to the garbage collector that pause times of nnn milliseconds or less are desired.

The throughput goal is measured in terms of the time spent collecting garbage and the time spent outside of garbage collection (referred to as application time). The goal is specified by the command-line option -XX:GCTimeRatio=<nnn>.

27. What is the default garbage collector in Java?

In Java 7 and 8, it is parallel GC while from Java 9 onwards it is Garbage first (G1) GC.

28. Explain Serial garbage collector.

The serial collector uses a single thread to perform all garbage collection work, which makes it relatively efficient because there is no communication overhead between threads. It is best-suited to single processor machines, also can be useful on multiprocessors for applications with small data sets (up to approximately 100 MB). The serial collector is selected by default on certain hardware and operating system configurations, or can be explicitly enabled with the option -XX:+UseSerialGC.

29. How to find which Garbage collector is running?

Using the below JVM parameter will print the default ergonomic values.

java -XX: +PrintCommandLineFlags -version
30. Is objects with circular reference, object linked to each other, garbage collected?

Yes. GC handles circular reference.

31. Explain JVM Escape Analysis.

Escape analysis is a technique by which the Java Hotspot Server Compiler can analyze the scope of a new object's uses and decide whether to allocate it on the Java heap.

Escape analysis determines the object's escape state which is one of the following.

GlobalEscape: An object escapes the method and thread. For example, an object stored in a static field, or, stored in a field of an escaped object, or, returned as the result of the current method.

ArgEscape: An object that is passed as an argument to a method but cannot otherwise be observed outside the method or by other threads.

NoEscape: An object that cannot escape the method or thread at all.

«
»
Programs

Comments & Discussions