directory

1. Briefly describe the Java garbage collection mechanism

2. What is GC? Why GC

3. The advantages and principles of garbage recycling. Two recycling mechanisms are considered

4. What is the basic principle of garbage collector? Can the garbage collector reclaim memory right away? Is there any way to proactively notify the virtual machine for garbage collection?

5. What reference types are available in Java?

6. How to determine whether an object can be reclaimed?

7. When can objects be garbage collected in Java

8. Does garbage collection occur in persistent generations in the JVM

What garbage collection algorithms does the JVM have?

What garbage collectors does the JVM have?

How about CMS garbage collector?

12. What are the new generation garbage recyclers and old garbage recyclers? What’s the difference?

13. Describe how generational garbage collector works.

1. Briefly describe the Java garbage collection mechanism

In Java, programmers do not need to display to free the memory of an object, but the virtual machine does it itself. In the JVM, there is a garbage collection thread, which is low priority and does not execute under normal circumstances, but only when the VIRTUAL machine is idle or the current heap is out of memory, which sweeps through objects that are not referenced by any of them and adds them to the collection for collection.

2. What is GC? Why GC

GC stands for Gabage Collection, and memory handling is where programmers tend to have problems, forgotten or incorrect memory

Collection can lead to instability or even crash of a program or system, and Java provides GC capabilities that automatically detect whether an object is out of scope

For the purpose of reclaiming memory, the Java language does not provide a display operation to free allocated memory.

3. The advantages and principles of garbage recycling. Two recycling mechanisms are considered

The most notable feature of the Java language is the introduction of garbage collection, which allows Java programmers to write programs without thinking about memory management.

Because of this garbage collection mechanism, objects in Java no longer have the concept of “scope”; only referenced objects have “scope”.

The garbage collection mechanism effectively prevents memory leaks and can effectively use available memory.

The garbage collector typically runs as a single low-level thread that cleans and reclaims objects in the memory heap that have died or not been used for a long time under unpredictable circumstances.

A programmer cannot call the garbage collector for an object or all objects in real time.

Garbage collection includes generational replication garbage collection, tag garbage collection, and incremental garbage collection.

4. What is the basic principle of garbage collector? Can the garbage collector reclaim memory right away? Is there any way to proactively notify the virtual machine for garbage collection?

In the case of the GC, when a programmer creates an object, the GC starts monitoring the address, size, and usage of the object.

In general, GC records and manages all objects in the heap in a directed graph. This is a way to determine which objects are “reachable” and which are “unreachable”. When the GC determines that some objects are “unreachable”, it is the GC’s responsibility to reclaim those memory Spaces.

You can. Programmers can manually execute System.gc() to tell the GC to run, but the Java language specification does not guarantee that the GC will execute.

5. What reference types are available in Java?

  • Strong references: No collection occurs when gc occurs.
  • Soft references: useful but not required objects that are reclaimed before an overflow occurs.
  • Weak references: Useful but not required objects that will be collected in the next GC.
  • Virtual reference (ghost reference/PhantomReference) : objects cannot be obtained by virtual reference. Virtual reference is implemented by PhantomReference. The purpose of the virtual reference is to return a notification on gc.

6. How to determine whether an object can be reclaimed?

Garbage collector in the garbage collection, the first need to determine which memory is to be reclaimed, which objects are “alive”, can not be reclaimed; Which objects are “dead” and need to be recycled.

There are two ways to judge:

  • Reference counter method: create a reference count for each object, count +1 when there is an object reference, count -1 when the reference is released, and can be reclaimed when the counter is 0. It has a disadvantage that it does not solve the problem of circular references;
  • Reachability analysis algorithm: Search down from GC Roots, and the search path is called reference chain. When an object is not connected to GC Roots by any reference chain, the object is proven to be recyclable.

7. When can objects be garbage collected in Java

When an object becomes untouchable to the application that currently uses it, it can be reclaimed.

Garbage collection does not occur in the permanent generation, and Full garbage collection (Full GC) is triggered if the permanent generation is Full or the threshold is exceeded. If you look closely at the output from the garbage collector, you will see that persistent generations are also collected. This is why the correct permanent generation size is important to avoid Full GC.

8. Does garbage collection occur in persistent generations in the JVM

Garbage collection does not occur in the permanent generation, and Full garbage collection (Full GC) is triggered if the permanent generation is Full or the threshold is exceeded. If you look closely at the output from the garbage collector, you will see that persistent generations are also collected. This is why the correct permanent generation size is important to avoid Full GC. See Java8: from persistent generation to metadata section

Java8 has removed the permanent generation and added a native memory area called the metadata area.

What garbage collection algorithms does the JVM have?

  • Mark-sweep algorithm: Marks unwanted objects and then collects them. Disadvantages: Inefficient, unable to remove garbage debris.
  • Copy algorithm: divide two memory areas of equal size according to the capacity. When one area is used up, the living objects are copied to the other area, and then the used memory space is cleared once. Disadvantages: Low memory usage, only half of the original.
  • Mark-declutter algorithm: Marks useless objects, moves all surviving objects towards one end, and then clears memory directly beyond the end boundary.
  • Generation algorithm: according to the different life cycle of the object, the memory is divided into several blocks, generally the new generation and the old age. The new generation basically adopts the replication algorithm, and the old age adopts the tag sorting algorithm.

Mark-clear algorithm

Mark unwanted objects and then recycle them.

Mark-sweep is a common basic garbage collection algorithm that divides garbage collection into two phases:

  • Mark stage: Mark objects that can be recycled.
  • Cleanup phase: Reclaim space occupied by marked objects.

The mark-sweep algorithm is fundamental because all the garbage collection algorithms that follow are improved upon it.

Advantages: Simple implementation, no object to move.

Disadvantages: Inefficient marking and cleaning process, resulting in a large number of discontinuous memory fragments, improve the frequency of garbage collection.

The execution process of the mark-clear algorithm is shown below

Replication algorithm

In order to solve the problem of low efficiency of mark-clear algorithm, a copy algorithm was developed. It divides the memory space into two equal areas and uses only one of them at a time. Garbage collection iterates through the currently used region, copies live objects to another region, and finally collects recyclable objects from the currently used region.

Advantages: Memory can be allocated sequentially, simple implementation, efficient operation, do not consider memory fragmentation.

Disadvantages: The available memory size is reduced by half, and objects are frequently copied when they have a high survival rate.

The execution process of the replication algorithm is shown in the following figure

Mark-collation algorithm

Replication algorithm can be used in the new generation, but cannot be selected in the old age, because the survival rate of objects in the old age will be higher, so there will be more replication operations, resulting in low efficiency. Mark-clear algorithm can be used in the old era, but it is not efficient, and it is easy to generate a large number of memory fragments after memory reclamation. Therefore, a mark-compact algorithm emerged. Unlike mark-compact algorithm, after marking the recyclable objects, all the surviving objects are compressed to one end of memory, so that they are Compact together, and then the memory beyond the end boundary is reclaimed. After collection, used and unused memory are on separate sides.

Advantages: It solves the memory fragmentation problem of mark-clean algorithm.

Disadvantages: Local object movement is still needed, which reduces efficiency to a certain extent.

The execution process of the mark-collation algorithm is shown in the figure below

Generational collection algorithm

Currently, all commercial VMS use the garbage collection algorithm of generational collection. The generational collection algorithm, as its name implies, divides memory into chunks based on the lifetime of objects. Generally including young generation, old generation and permanent generation, as shown in the figure:

What garbage collectors does the JVM have?

If the garbage collection algorithm is the methodology of memory collection, then the garbage collector is the concrete implementation of memory collection. The figure below shows 7 collectors that operate on different generations, including the Serial, PraNew, and Parallel Avenge collectors, and the Serial Old, Parallel Old, AND CMS collectors. There is also a G1 collector for recycling the entire Java heap. The wiring between different collectors indicates that they can be used together.

  • Serial collector (copy algorithm): the new generation of single-threaded collector, marking and cleaning are single-threaded, the advantage is simple and efficient;
  • ParNew collector (copy algorithm): A new generation of delegate parallel collector, which is actually a multi-threaded version of Serial collector and performs better than Serial on multi-core CPUS;
  • The Parallel Collector. A new generation of Parallel collectors, driven by the pursuit of high throughput and efficient CPU utilization. Throughput = user thread time /(user thread time +GC thread time), high throughput can efficiently use THE CPU time, as soon as possible to complete the calculation tasks of the program, suitable for background applications such as the corresponding interaction requirements are not high scenes;
  • Serial Old collector (mark-collation algorithm): Old single-threaded collector, older version of Serial collector;
  • The Parallel Old Collector (mark-collation algorithm) : the Parallel Collector, throughput first, older version of the Parallel Avenge collector;
  • CMS(Concurrent Mark Sweep) collector (mark-sweep algorithm) : The old parallel collector aims at obtaining the shortest collector pause time. It has the characteristics of high concurrency and low pause, and pursues the shortest COLLECTOR pause time.
  • G1(Garbage First) : the Java heap parallel collector. The G1 collector is a new collector in JDK1.7. The G1 collector is based on the “mark-collation” algorithm, that is, does not generate memory fragmentation. In addition, the G1 collector differs from its predecessors in that it collects the entire Java heap (including the new generation and the old generation), whereas the first six collectors only collect the new generation or the old generation.

How about CMS garbage collector?

CMS, short for Concurrent mark-sweep, is a garbage collector that achieves the shortest collection pause time at the expense of throughput. This garbage collector is ideal for applications that require fast server response. Specify the use of the CMS garbage collector by adding “-xx :+UseConcMarkSweepGC” to the start JVM argument.

CMS uses the mark-clear algorithm to achieve, so a large number of memory fragments will be generated during GC. When the remaining memory cannot meet the program running requirements, the system will suffer Concurrent Mode Failure. The Serial Old collector is used by the temporary CMS for garbage removal, where performance is reduced.

12. What are the new generation garbage recyclers and old garbage recyclers? What’s the difference?

  • Cenozoic recyclers: Serial, ParNew, Parallel Insane
  • Old collector: Serial Old, Parallel Old, CMS
  • Whole heap collector: G1

The new generation garbage collector generally adopts replication algorithm. The advantage of replication algorithm is high efficiency, but the disadvantage is low memory utilization. Old-time recyclers generally use a mark-collation algorithm for garbage collection.

13. Describe how generational garbage collector works.

The generation collector has two partitions: old generation and new generation. The default space of the new generation is 1/3 of the total space, and the default space of the old generation is 2/3.

The new generation uses the replication algorithm, and there are three partitions in the new generation: Eden, To Survivor, and From Survivor. Their default ratio is 8:1:1. Its execution process is as follows:

  • Put Eden + From Survivor into To Survivor zone;
  • Clear Eden and From Survivor partitions;
  • Swap From Survivor and To Survivor partitions, From Survivor To Survivor, To Survivor To Survivor From Survivor.

An object that survives every move From Survivor To Survivor is aged +1 and is upgraded To the old generation when age reaches 15 (the default is 15). Large objects also go directly to old generation.

The old generation triggers global garbage collection when the footprint reaches a certain value, usually using a mark-up execution algorithm. These iterations constitute the entire implementation process of generational garbage collection.


In addition to these, I have also compiled the classic 2021 Java Engineer interview questions and study notes. There are 485 pages of approximately 850 interview questions with answers in PDF. Java, MyBatis, ZooKeeper, Dubbo, Elasticsearch, Memcached, Redis, MySQL, Spring, Spring Boot, Spring Cloud, RabbitMQ, Kafka, Linux Etc on almost all technology stacks.

Each technology stack has no less than 50 classic interview questions and study notes, dare not say brush package you into the big factory, just let you face the interviewer more confidence or no problem.