Week 25 — What is a garbage collector and why do we use them?
Question of the Week #25
What is a garbage collector and why do we use them?
10 Replies
In order to collect garbage memory and clean them automatically.Or else we need to free the memory by ourselves and it will occupy a lot of effort
Submission from Flaming#3109
Garbage collection helps developer to avoid a slew of memory based errors. From memory leaks, accessing freed memory or bad pointer arithmetic manifesting after a program has already been running.
Submission from Chowder#5643
The java garbage collector automatically detects unused objects in the Memory and frees memoryspace by deleting the unused object in memory while the program is running.
For example, when there is an unused instance of a class in the program, the garbage collector will automatically detect it when the program is started. This makes the program use less unneccesary objects and thus lets the program run more fluently
Submission from philipp#7125
A garbage collector frees up ram that had been allocated to previous tasks without having to manually alcoate ram making programming quicker but can result in ram overloading problems. In programming languages like C there is no garbage collector and ram has to be allocated manually making it more difficult for beginners to learn.
Submission from PinguDev#2032
In Java, garbage means unreferenced objects. Garbage Collection is the process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. This makes Java memory efficient because the garbage collector removes the unreferenced objects from heap memory.
Here’s an example of garbage collection in Java:
public class TestGarbage1 {
public void finalize() {
System.out.println("object is garbage collected");
}
public static void main(String args[]) {
TestGarbage1 s1 = new TestGarbage1();
TestGarbage1 s2 = new TestGarbage1();
s1 = null;
s2 = null;
System.gc();
}
}
In this example, two objects s1 and s2 are created and then set to null, making them eligible for garbage collection. The System.gc() method is then called to invoke the garbage collector.
Submission from honey1910#5814
What is a garbage collector and why do we use it?
- The garbage collector is responsible for the automatic memory management, with its primary goal to reclaim memory occupied by objects, that are no longer in use, which frees up resources and prevents memory leaks.
How does the GC work?
- The GC works by automatically indentifying and collecting objects that are no longer reachable or referenced by any part of the program, allowing devs to focus on writing the application logic rather than managing memory explicitly.
- Traversing the object graph, starting from the root objects (global variables, local variables on the call stack, and static fields) and determining which objects are still in use - objects that are not reachable are considered garbage and are eligible for collection.
Code example
Submission from Denis Z.#0177
A garbage collector automatically deletes variables that are no longer used in order to clear up memory in your computer. Some programming languages like Python and Java have these automatic garbage collectors, whereas programming languages like C you have to delete the variable yourself.
Submission from JebTownhouse529#5651
Garbage collecting is a memory management concept, that frees an element when all references to it have been lost. This is also what java is doing.
Java's garbage collector runs every time space needs to be freed, for example when your program begins to run out of memory. It looks at every registered element in its memory, and looks through the amount of references to that specific element. If there are no references anymore, the element is removed from memory.
Garbage collecting languages allow you to stop worrying about manual memory management. Languages like C do not garbage collect by default tho, which is why malloc() and free() exist: you have to manage the memory yourself.
Languages like rust use a borrow checker, which can figure out when references to variables or other elements get lost, then insert a clever free() when all references get lost.
⭐ Submission from 0x150#9699
When allocating memory on the heap in a language like C or C++, the developer needs to make a decision how long that memory segment should be available. When the memory is not needed, the developer needs to free it.
This could get complicated and error-prone, especially in large systems.
Using some data after it has been
free()
d can lead to crashes, hard-to-diagnose bugs or security vulnerabilities (up to remote code execution).
On the other side, when memory is not free()
d, a memory leak occurs leading to memory being wasted that cannot be reclaimed by the OS (the application consumes more memory than required and this gets worse after time).
In Java, the developer garbage collector (GC) automatically frees memory when it is not used any more. Developers can create objects as they like and the garbage collector will clean them up eventually when they are not used any more.
This only happens when the GC is sure the object is not in use any more
The following garbage collectors are available in Java:
- G1 (standing for "Garbage first") is the default garbage collector in newer Java versions most of the time (in some cases (e.g. there is not much memory available), another GC might be the default). G1 aims to be a balance between throughput, latency and footprint.
- The Serial GC does garbage collection in a single thread while stopping the whole Java program ("stop the world") during that process.
- Parallel GC is similar to the Serial GC but uses multiple garbage collection threads. This is useful for batch processes.
- Shenandoah is a low-latency garbage collector. It is worth considering when pause times are critical.
- ZGC is another low-latency GC but it offers sub-millisecond pause times, even with heaps up to multiple Terrabytes. This is possible because almost of of the GC work is done concurrently while the application keeps running allowing pause times to be constant with regard to heap size.
- The Epsilon GC is a no-op GC meaning it does not free up any memory. This might seem contradictory but it can be useful for testing (as a baseline when doing performance measurements or GC tuning). It can also be useful for real-time applications that can be restarted regularly (e.g. every day or when the memory is higher than a specific threshold)An important concept in Java garbage collection is the weak generational hypothesis. In typical Java applications, most objects are short-lived and objects that have been reachable for a long time are likely still reachable for for some time.
This is why generational garbage collectors are splitting objects into multiple generations. When objects are created, they are put into the young generations. Once an object "survives" a specific number of garbage collections (meaning it is still reachable), it is put into the old generation.
Generational GCs then clean up the young generations (with lots of new objects) frequently and only rarely do a full collection which also runs over the old generation.
With Java 21, ZGC will be a generational GC. Similarly, an experimental option for making Shenandoah generational will be introduced.
⭐ Submission from dan1st#7327