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
Eric McIntyre
Eric McIntyre2y ago
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
Eric McIntyre
Eric McIntyre2y ago
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
Eric McIntyre
Eric McIntyre2y ago
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
Eric McIntyre
Eric McIntyre2y ago
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
Eric McIntyre
Eric McIntyre2y ago
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
Eric McIntyre
Eric McIntyre2y ago
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
public class GarbageCollectorExample {

public static void main(String[] args) {
// Creating two new objects of the MyClass class
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();

// Setting obj2 to reference to nothing, so as to show how gc works - it will collect that object
obj2 = null;

// Requesting garbage collection explicitly
System.gc();
}

static class MyClass {
// Class implementation
}

@Override
protected void finalize() throws Throwable {
// Clean-up code executed before gc. => This is the code that you can write to perform any necessary clean-up or resource deallocation before an object is garbage collected.
// This method is called before reclaiming memory, which you can also perform resource deallocation or cleanup operationsin this method.
// Also, while people say that It's generally recommended to avoid relying on finalize() for critical operations, you can always use it if you wish to do so.

// Call the super class finalize() method to execute it.
super.finalize();
}
}
public class GarbageCollectorExample {

public static void main(String[] args) {
// Creating two new objects of the MyClass class
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();

// Setting obj2 to reference to nothing, so as to show how gc works - it will collect that object
obj2 = null;

// Requesting garbage collection explicitly
System.gc();
}

static class MyClass {
// Class implementation
}

@Override
protected void finalize() throws Throwable {
// Clean-up code executed before gc. => This is the code that you can write to perform any necessary clean-up or resource deallocation before an object is garbage collected.
// This method is called before reclaiming memory, which you can also perform resource deallocation or cleanup operationsin this method.
// Also, while people say that It's generally recommended to avoid relying on finalize() for critical operations, you can always use it if you wish to do so.

// Call the super class finalize() method to execute it.
super.finalize();
}
}
Submission from Denis Z.#0177
Eric McIntyre
Eric McIntyre2y ago
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
Eric McIntyre
Eric McIntyre2y ago
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.
String s = "abc"; // String instance, one reference: variable s
s = s + "def"; // Original string instance "abc" is lost, new string instance "abcdef" is stored. Original "abc" is now floating in memory without references
System.gc(); // tells the system to run the garbage collector prematurely; "abc" instance is removed from memory
String s = "abc"; // String instance, one reference: variable s
s = s + "def"; // Original string instance "abc" is lost, new string instance "abcdef" is stored. Original "abc" is now floating in memory without references
System.gc(); // tells the system to run the garbage collector prematurely; "abc" instance 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
Eric McIntyre
Eric McIntyre2y ago
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.
YOUR_DATA_TYPE* someMemory = (YOUR_DATA*) malloc(sizeof(YOUR_DATA_TYPE));//allocate memory
//use the memory somehow
//...
free(someMemory);//give back the memory to the operating system
YOUR_DATA_TYPE* someMemory = (YOUR_DATA*) malloc(sizeof(YOUR_DATA_TYPE));//allocate memory
//use the memory somehow
//...
free(someMemory);//give back the memory to the operating system
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
Object o = new Object();//create some object stored on the heap
//use the object somehow
//...
//no need to free it - the GC does this for you
Object o = new Object();//create some object stored on the heap
//use the object somehow
//...
//no need to free it - the GC does this for you
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)
Eric McIntyre
Eric McIntyre2y ago
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
Want results from more Discord servers?
Add your server