<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Recep Akkuş on Medium]]></title>
        <description><![CDATA[Stories by Recep Akkuş on Medium]]></description>
        <link>https://medium.com/@recepefendi7?source=rss-63cf706d60bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bI8qLhsKz6lULrIomlvYZQ.gif</url>
            <title>Stories by Recep Akkuş on Medium</title>
            <link>https://medium.com/@recepefendi7?source=rss-63cf706d60bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:26:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@recepefendi7/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Garbage Collector: A Complete Guide from Memory Management to Modern Garbage Collection Algorithms]]></title>
            <link>https://medium.com/@recepefendi7/garbage-collector-a-complete-guide-from-memory-management-to-modern-garbage-collection-algorithms-5915bd9cabd2?source=rss-63cf706d60bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5915bd9cabd2</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Recep Akkuş]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 08:41:12 GMT</pubDate>
            <atom:updated>2026-08-06T08:50:28.651Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Foreword</strong></h3><p>When we first start developing software, memory management often seems like an invisible mechanism running in the background. We create an object, use it, and after a while, it disappears. Especially for developers working in languages like Java, C#, Go, or JavaScript, this process is so automated that the question “When was this object removed from memory?” rarely even comes up.</p><p>This is where the Garbage Collector comes into play.</p><p>However, the Garbage Collector is not merely a “garbage collector” that deletes unused objects. To truly understand it, we need to examine how memory works, how the operating system manages processes, what responsibilities the runtime has, and how different programming languages approach memory management.</p><p>The purpose of this article is not merely to explain the Garbage Collector through the lens of a specific programming language; rather, it is to build the topic step by step, starting from the most fundamental level, and to present the big picture. Therefore, we will first get to know memory, then see why memory management is a difficult problem, and subsequently examine how the Garbage Collector works and which algorithms it uses. Finally, we’ll compare how different programming languages solve the same problem in different ways.</p><p>While preparing this article, I adhered to a single principle:</p><p><strong>No concept will be explained without first providing the necessary background knowledge to understand it.</strong></p><p>For this reason, I followed a natural sequence of concepts throughout the article as much as possible. Each section was designed to lay the foundation for the next. My goal was not merely to explain how a garbage collector works, but also to explain why it was designed that way.</p><p>If, by the end of this article, you can comfortably explain how a garbage collector scans memory, why different algorithms are needed, and why different programming languages adopt different approaches to memory management, then this article has achieved its purpose.</p><p>Enjoy the read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2ULj7DF1ErlqEXOaR8CrQ.png" /></figure><h3><strong>Chapter 2: Understanding Memory:</strong></h3><p>Before we can begin to understand how the Garbage Collector works, we need to understand the environment in which it operates. This is because the Garbage Collector is not a magical mechanism that operates on its own; it analyzes the memory used by a program during execution and attempts to remove objects that are no longer needed from that memory.</p><p>This means that if we do not know what memory is, how a program uses memory, and how data is stored there, we cannot fully understand how the Garbage Collector makes its decisions.</p><p>For this reason, in this section we will first explore computer memory. We will examine, step by step, how RAM works, how data is represented in memory, how a program uses memory, and how the operating system manages this process. This will provide a solid foundation for the Garbage Collector mechanism we will discuss in the following sections.</p><h4><strong>2.1 What Is Memory?</strong></h4><p>To understand how the Garbage Collector works, we must first define the environment in which it operates. This is because the Garbage Collector is not a magical mechanism that operates on its own. It analyzes the data a program uses during execution, identifies objects that are no longer needed, and frees up the memory space occupied by these objects so it can be reused. Therefore, if we want to understand how the Garbage Collector makes its decisions, we must first answer this fundamental question:</p><p><strong>Where does a program store the data it uses while running?</strong></p><p>The answer to this question leads us to computer memory.</p><p>Every application we use today continuously generates data and updates existing data as long as it is running. Open tabs in a web browser, the exact second where you paused a video, your character’s position, health points, and inventory in a game, or unread messages in a messaging app… None of these consist solely of source code. The moment a program starts running, all of this information must be held by the computer, read when needed, and constantly updated.</p><p>At first glance, one might assume this information is stored on an SSD or HDD. After all, that’s where we store our documents, photos, and programs. However, storage devices and memory do not serve the same purpose. Storage devices like SSDs and HDDs are designed to retain data even after the computer is turned off. In contrast, the processor must access the same data billions of times per second while performing calculations. If the processor tried to read every piece of data it needed directly from the SSD, the computers we use today would be so slow as to be practically unusable.</p><p>For this reason, computer architecture includes a separate workspace that the processor can access much more quickly. This workspace is <strong>called memory</strong>.</p><p>In the broadest sense, <strong>memory is the workspace that temporarily stores the data a program needs while it is running.</strong> Variables, objects, arrays, text, and calculation results created while a program is running are first placed in memory. When the processor needs to perform an operation, it reads the required data from here, performs the calculation, and writes the resulting value back to memory. In other words, memory holds the active data set the processor is working on.</p><p>Let’s consider a simple example.</p><pre>int score = 150;</pre><p>When this line is compiled, it is not merely a line of source code. When the program starts running, a specific area in memory is allocated for the variable named `score`, and the value 150 is written to that area. Subsequently, as the program reads or modifies this value, the processor continuously operates on the same memory location. The number you see on the screen is actually just a reflection of this value stored in memory.</p><p>Similarly, characters created in a game engine, physics calculations, particle effects, artificial intelligence states, and user interface components are also stored in memory. As long as the program is running, this data is constantly being created and modified, and some of it becomes completely obsolete when it is no longer needed.</p><p>These are precisely the objects the Garbage Collector deals with. The Garbage Collector does not concern itself with files stored on the disk. It does not delete photos from your computer or organize your documents. Its scope of operation is limited solely to the memory of the running program. Therefore, understanding what memory is constitutes the first and most important step in grasping how the Garbage Collector works.</p><p>There is one more point to note here. So far, we’ve treated memory solely as a <strong>workspace</strong>. We haven’t yet examined how this space is physically constructed, how data is actually stored, or how the processor accesses memory. This is because each of these is a fundamental topic that requires its own explanation.</p><p>In the next section, we’ll examine <strong>RAM</strong>, the hardware counterpart of memory. Once we learn how a bit is physically stored, the roles of transistors and capacitors in this process, and why the processor can access memory so quickly, we’ll be able to see much more clearly why the Garbage Collector operates directly on this structure.</p><h4><strong>2.2 The Concepts of Bytes and Addresses: Memory Addressing and Pointers</strong></h4><p>In the previous section, we learned that RAM consists of millions of memory cells and that these cells store data. However, a new problem arises. If there are billions of bytes in memory, how does the processor find the data it is looking for?</p><p>The answer lies in <strong>memory addresses</strong>.</p><p>Every <strong>byte</strong> in memory has its own unique address. These addresses are numbers that represent their locations in memory. When the processor wants to access a piece of data, it uses the address where that data is located, not the variable name.</p><p>We can think of this using the example of an apartment building. Many people with the same name may live in a city. However, every apartment has a unique address. The mail carrier delivers a letter based on the address rather than the name. Computers work in a similar way; variable names are meaningful to the programmer, but for the processor, only the addresses matter.</p><p>For example, let’s consider the following code:</p><pre>int score = 150;</pre><p>We access this variable using the name “score.” However, once compilation is complete and the program runs, the processor does not recognize the name “score.” What it knows is that this value is located at an address in memory, such as 0x7FFE1234.</p><p>In reality, the situation is roughly as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYEib2tedCEZAjUcqNVoBQ.png" /></figure><p>Here, the “0x” prefix indicates that the address is represented in the<strong> hexadecimal </strong>number system. In the world of programming, memory addresses are generally written in this format because it offers a much more readable form compared to the binary number system.</p><p>So what happens if a program needs to know the location of another piece of data?</p><p>This is where the concept of a <strong>pointer</strong> comes into play.</p><p>A pointer, in its simplest definition, <strong>is a variable that stores the memory address of another piece of data.</strong></p><p>For example:</p><pre>int score = 150;<br><br>int* ptr = &amp;score;</pre><p>In this code, ptr does not store the value 150. Instead, it stores the memory address where the score variable is located.</p><p>We can think of memory like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLPd-NgOlDP5rHtbDhY_Nw.png" /></figure><p>Here, the value of the ptr variable actually points to another address.</p><p>At first glance, this might seem unnecessary. After all, we already have the `score` variable. Why keep its address as well?</p><p>Because most modern software doesn’t work with a fixed amount of data. In a game engine, characters, user interface components, physics objects, or dynamically created data structures are constantly being created, linked together, and destroyed as needed. For these objects to establish relationships with one another, they must know each other’s locations in memory.</p><p>In other words, objects in software recognize each other not by their names, <strong>but by their addresses.</strong></p><p>This point is of critical importance from the Garbage Collector’s perspective. This is because the Garbage Collector does not concern itself with variable names. Instead, it tracks which addresses in memory refer to which objects. If an object can no longer be reached from any address, it is considered <strong>unreachable</strong> and can subsequently be removed from memory.</p><p>For now, we won’t examine how the concept of “reachability” is determined. However, we can now begin to understand why the Garbage Collector operates based on addresses and references.</p><p>In the next section, we’ll see that the memory used by a program is not a single contiguous block. The operating system divides memory into various regions for different purposes. <strong>Code, global variables, dynamic objects, and function calls are not stored in the same place.</strong> This distinction is crucial for understanding which memory areas the Garbage Collector deals with. Therefore, in the next section, we will examine the concept of <strong>Process Memory Layout.</strong></p><h4><strong>2.3 Process Memory Layout</strong></h4><p>So far, we have treated memory as a single workspace. In reality, however, the operating system does not leave the memory allocated to a program as a single contiguous block. Instead, it divides memory into regions that serve different purposes. This organization is called the <strong>Process Memory Layout.</strong></p><p>Every running program has its own virtual address space, which is divided into specific sections. Each section has a different function. Some store the program’s code, some hold global variables, and others store data created during execution.</p><p>In general, a program’s memory layout is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFPp48Ni25Ev8ZqBQ8Nyxw.png" /></figure><p>These sections have different responsibilities.</p><p><strong>The Text Segment</strong>, contains the compiled program code. The machine instructions executed while the program is running are located here.</p><p><strong>The Data Segment</strong>, stores global and static variables that have been initialized.</p><p><strong>The BSS Segment</strong>, is reserved for global and static variables that have not been initialized. This area is zeroed by the operating system when the program starts.</p><p><strong>The Heap</strong>, is the region where objects created dynamically during runtime are located. The programmer or the runtime system allocates memory from this area as needed. This is also the area the Garbage Collector focuses on the most.</p><p><strong>The Stack</strong>, on the other hand, stores temporary data created during function calls. When a function begins execution, the information it needs is placed on the Stack; when the function ends, this area is automatically reclaimed.</p><p>For now, we will not examine in detail how these sections work. Our goal here is simply to see that program memory is not a single large area, but consists of parts that perform different tasks.</p><p>This distinction is particularly important from the perspective of the Garbage Collector. This is because the Garbage Collector does not manage the entire memory. For example, the <strong>Text Segment</strong>, where the program’s machine code is located, or the data on the <strong>Stack</strong> in most cases, are not under the Garbage Collector’s responsibility. Its primary area of operation is the <strong>Heap</strong> region, where dynamically created objects are located.</p><p>In the next section, we will see why physical memory alone is not sufficient. This is because operating systems do not directly expose physical RAM to programs. Instead, they provide each program with its own <strong>virtual address space (Virtual Memory)</strong>. The addresses that the Garbage Collector sees are actually these virtual addresses. For this reason, in the next section, we will examine the concept of <strong>Virtual Memory.</strong></p><h4><strong>2.4 Virtual Memory: Page Table, MMU, and Physical RAM</strong></h4><p>In the previous section, we saw that the memory of a running program is divided into different regions, such as the <strong>Stack, Heap, </strong>and<strong> Data Segment.</strong> However, this raises an important question:</p><p><strong>Are these memory addresses actually real addresses within RAM?</strong></p><p>At first glance, one might think so. After all, the program writes data to memory, and the processor reads this data from RAM. However, modern operating systems actually use a very different method.</p><p>They do not give a program direct access to physical RAM.</p><p>Instead, they provide each program with its own <strong>virtual address space</strong> that appears to be contiguous. While the program is running, it believes that all the addresses it uses belong to it. In reality, however, behind these addresses lies an entirely different physical memory layout managed by the operating system.</p><p>We can think of this using the example of a hotel. Every hotel may have a room numbered 101. However, “101” is merely an internal numbering system within the hotel; rooms numbered 101 around the world are not the same physical room. The addresses used by programs work in a similar way. Each process runs in its own independent address space.</p><p>One of the greatest advantages of this approach is isolation. The addresses in one program’s memory cannot be directly viewed or modified by another program. Thus, an error in one application does not corrupt the memory of other applications, and operating system security is largely preserved.</p><p>So how do these virtual addresses used by a program map to actual locations in physical RAM?</p><p>This conversion is performed by a special piece of hardware within the processor called the <strong>Memory Management Unit (MMU). </strong>When the processor wants to access a memory address, the MMU is activated first. The MMU consults a table prepared by the operating system, called the Page Table, to determine which physical section of RAM corresponds to the relevant virtual address. The read or write operation is then performed on the actual RAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38tjm1res27DMMMARWnDsQ.png" /></figure><p>This process is completely invisible to the programmer. When you access a variable, you do not perform the address translation yourself; the processor and the operating system automatically handle this for you.</p><p>This architecture does more than just ensure security. It also enables more efficient use of physical memory, allows unused pages to be moved to disk when necessary, and enables each program to run as if it had a large block of memory allocated exclusively to itself.</p><p>From the perspective of the garbage collector, the key point is this: The garbage collector does not concern itself with the actual addresses in physical RAM. It tracks objects through the virtual addresses seen by the running program. An object’s physical location in memory may change; however, what matters to the program are the <strong>virtual addresses</strong> and reference relationships that allow it to access that object.</p><p>In this section, we learned the basic principles of virtual memory. We now understand how a computer organizes its memory and how programs access it. In the next main section, we’ll shift our focus from the operating system to the program and examine how a program uses this memory. In particular, we’ll explore step by step why the <strong>Stack</strong> and <strong>Heap</strong>regions exist, how they work, and why the Garbage Collector deals only with specific memory areas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqWrUGmio2cYg8kNVuiXkA.png" /></figure><h3><strong>3. How Do Programs Use Memory?</strong></h3><p>In the previous section, we saw how a computer’s memory is organized and how the operating system allocates memory space to programs. However, the mere existence of memory is not enough on its own. What really matters is how a running program uses that memory.</p><p>From the moment a program starts running, it continuously generates new data. Functions are called, variables are created, objects are instantiated, and some are destroyed when they are no longer needed. Throughout this entire process, the program uses different regions of memory for different purposes.</p><p>However, not all data is created in the same way or has the same lifespan.</p><p>For example, a local variable defined within a function exists only as long as that function is running. In contrast, an object created by the user may have a much longer lifespan, persisting until the application closes.</p><p>So why isn’t data with such different lifespans stored in the same place?</p><p>The answer to this question leads us to the concepts of the <strong>Stack</strong> and the <strong>Heap</strong>. Modern operating systems and runtimes improve performance and make memory usage more efficient by managing short-lived and long-lived data in different memory regions.</p><p>In this section, we’ll first examine why the <strong>Stack</strong> exists, how function calls are represented in memory, and how the computer returns to where it left off after a function completes. Then, we’ll explore step by step why the <strong>Heap</strong> is necessary, how dynamic memory allocation works, and why the Garbage Collector operates specifically on the Heap.</p><h4><strong>3.1 What Happens When a Function Is Called?</strong></h4><p>Calling a function is an extremely natural part of writing a program. In fact, most of the time we don’t even think about how it happens.</p><p>For example, let’s consider the following C++ code:</p><pre>void Print()<br>{<br>  std::cout &lt;&lt; &quot;Hello World!&quot;;<br>}<br><br>int main()<br>{<br>  Print();<br>}<br></pre><p>From our perspective, all that happens is that the Print() function is called. A line of code executes, “Hello World!” is printed to the screen, and the program continues from where it left off.</p><p>However, from the computer’s perspective, the situation is much more complex.</p><p>When the processor switches to the Print() function, it doesn’t just start executing the new lines of code. It also has to remember where it was. This is because, once the function completes, it must return to the main() function and continue executing from where it left off.</p><p>This raises an important question:</p><p>How does the computer remember where to return?</p><p>Moreover, this isn’t limited to just a single function.</p><p>Let’s look at the following example:</p><pre>void C()<br>{<br>}<br><br>void B()<br>{<br>  C();<br>}<br><br>void A()<br>{<br>  B();<br>}<br><br>int main()<br>{<br>  A();<br>}</pre><p>Here, the processor is first inside main(). It then moves to the A() function, from there to B(), and finally reaches C().</p><p>So where will it return after C() is complete?</p><p>First to B()…</p><p>Then to A()…</p><p>And finally back to the main() function…</p><p>The computer must remember this sequence in its entirety. Otherwise, the program cannot run correctly.</p><p>Moreover, this isn’t the only information that needs to be preserved. Each function has its own parameters, local variables, and other information it needs during execution. When another function is called, this information must not be lost; it must remain available for use exactly as it was after the function completes.</p><p>Therefore, the processor needs a special mechanism to safely store this information for each function call.</p><p>The <strong>Call Stack</strong> forms the basis of this mechanism.</p><p>In the next section, we’ll examine the concept of a <strong>Stack Frame</strong> — which is created in memory during each function call — and see step by step how the computer stores this information.</p><h4><strong>3.2 What Is a Stack Frame?</strong></h4><p>In the previous section, we saw that after every function call, the computer must remember the location to return to and the information associated with that function. So how does it accomplish this?</p><p>Whenever a function is called, the computer gathers the information specific to that function into a small working area in memory. This area contains all the information necessary for the function to execute. Once the function is complete, this area is no longer needed and is removed from memory.</p><p>This temporary working area is called a <strong>stack frame.</strong></p><p>A stack frame does not just store local variables. It also contains the function’s parameters, the return address, and other operational information required by the compiler. Exactly which information is stored may vary depending on the processor architecture, operating system, and compiler. However, the basic idea remains the same: <strong>Every function call has its own independent working area.</strong></p><p>For example, consider the following code:</p><pre>void Sum(int a, int b)<br>{<br>  int total = a + b;<br>}</pre><p>When the Sum() function is called, a Stack Frame similar to the one below is created in memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWAPDJhLP9x8b-fgTCiM4A.png" /></figure><p>Thanks to this structure, the function can access all the information it needs from a single location. Once the function completes its execution, the Stack Frame is completely removed, and the memory it occupied becomes available for new function calls.</p><p>There is an important point to note here. <strong>Each function call creates its own new stack frame.</strong> Even if the same function is called consecutively or recursively, the information from the previous call is not overwritten. Instead, a separate stack frame is created for each call.</p><p>For example, consider the following function:</p><pre>void Print(int n)<br>{<br>  if(n == 0)<br>    return;<br><br>  Print(n - 1);<br>}</pre><p>When Print(3) is called, there is not just a single Stack Frame in memory. A new Stack Frame is created for each call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyp4vdhovWHI-Y3iLKj4pA.png" /></figure><p>Each has its own parameters, local variables, and return address. This allows functions to operate independently of one another and return to the correct point upon completion.</p><p>So how are these stack frames organized in memory? Where are they placed when a new function is called, and which one is removed first when the function ends?</p><p>The structure that manages this organization is the <strong>call stack.</strong> In the next section, we’ll examine how stack frames are stacked on top of one another and why they operate according to the <strong>LIFO (Last In, First Out)</strong> principle.</p><h4><strong>3.3 Heap</strong></h4><p>In the previous section, we saw that the <strong>stack</strong> is designed to manage temporary data needed during function calls. When a function starts, the necessary memory is allocated, and when the function ends, this space is automatically reclaimed. This approach is both very fast and extremely efficient.</p><p>However, not all data has a lifespan as short as that of a function.</p><p>Let’s imagine you’re developing a game. When a player enters the game, a character is created. This character stores its position, inventory, health, and much more in memory. Even after the function that creates the character has finished, this object must continue to exist. Otherwise, the character would disappear from memory the moment the function ends.</p><p>Similarly, a user object created in a banking application must continue to exist not just while the login function is running, but until the user logs out of the system.</p><p>This is where the Stack falls short.</p><p>The fundamental characteristic of the Stack is that it automatically frees the memory it allocates. While this behavior offers a significant advantage for short-lived data, it becomes a serious limitation for objects whose lifespan is determined at runtime. This is because the program cannot know in advance how long these objects will live.</p><p>To solve this problem, modern programming languages and operating systems use a second memory region called the <strong>Heap</strong>.</p><p>The heap is the area where the program can dynamically allocate the memory it needs during execution. When an object is created, it is placed in a memory block allocated for it on the heap. Unlike the stack, this memory is not automatically released when the function ends. The object continues to exist until it is explicitly freed or cleaned up by a memory management mechanism.</p><p>This feature makes the heap quite flexible. The program can create as many objects as it wants during execution, and the lifetimes of these objects can be completely independent of one another. However, this flexibility comes at a cost.</p><p>Since memory is managed automatically on the stack, the programmer hardly has to do anything. On the heap, however, a decision must be made regarding when allocated memory will be released. If this memory is not released in a timely manner, the program begins to consume more and more memory. Conversely, if a memory area that is still in use is released prematurely, the program may attempt to access invalid addresses, leading to unexpected errors.</p><p>Over the years, a large portion of the problems software developers have encountered — such as <strong>memory leaks, dangling pointers, </strong>and<strong> double free</strong> — have stemmed from this very issue.</p><p>This is precisely why the Garbage Collector was introduced.</p><p>The Garbage Collector’s primary area of operation is the <strong>heap</strong>. This is because objects with an indefinite lifespan are located here, and determining which objects are no longer in use is the most critical challenge of automatic memory management.</p><p>In the next section, we’ll examine how memory allocation is performed on the heap. Once we see what lies behind mechanisms like malloc, free, new, and delete, we’ll gain a much clearer understanding of exactly which problem the Garbage Collector is trying to solve.</p><h4><strong>3.4 Memory Allocation</strong></h4><p>In the previous section, we saw that objects whose lifetimes are determined at runtime are stored on the <strong>heap</strong>. However, it is incorrect to think of the heap merely as a “large block of memory.” A program cannot directly access the memory it needs from the heap. This memory must first be allocated.</p><p>This process is called <strong>Memory Allocation.</strong></p><p>Memory allocation is the process of reserving a memory block of the size required by the program and making that block available for the program’s use. For example, when you create an object or an array of unknown size during runtime, the program first searches the Heap for a sufficiently large empty area. When a suitable area is found, this region is allocated to the program and is now ready for use.</p><p>In languages such as C and C++, this process is directly under the programmer’s control.</p><pre>int* numbers = new int[100];<br><br>//or<br><br>int* numbers = (int*)malloc(sizeof(int) * 100);</pre><p>In both examples, the program requests a new memory block on the heap. Although how the allocated memory is used may differ, the basic idea is the same: The program requests a new area from the operating system or the memory manager during runtime.</p><p>However, there is an important detail here. When new or malloc is called, the operating system does not intervene directly every time.</p><p>In modern operating systems, <strong>system calls</strong> are quite costly. If a switch to the kernel were made for every memory request, program performance would drop significantly. For this reason, the runtime or standard library of most languages obtains larger memory blocks from the operating system and manages them internally. When a program creates a new object, space is usually allocated from this pre-allocated memory pool.</p><p>When communication with the operating system is required, different mechanisms are used depending on the platform. In Unix-like systems, while the `brk` and `sbrk` system calls were widely used in the past, <strong>mmap</strong> is now mostly preferred for large memory regions. On Windows, <strong>VirtualAlloc</strong> performs a similar function.</p><p>The programmer is often unaware of these details. They simply call new or malloc. However, behind the scenes, the allocator, the runtime, and the operating system work together to provide the program with the appropriate memory space.</p><p>It is also important to remember that memory allocation is only the first step. Once memory is allocated, it will be used for a period of time and then returned to the system. This is where the real challenge of memory management begins. If the timing and responsibility for freeing allocated memory cannot be determined correctly, many problems can arise, such as memory leaks, invalid pointers, and fragmentation.</p><p>This is precisely the fundamental problem that the Garbage Collector seeks to solve. Allocating memory is relatively easy; the real challenge lies in safely reclaiming memory that is no longer in use.</p><p>In the next section, we will examine the <strong>Static Memory</strong> region, which contains data whose lifetime spans the duration of the program. This will complete our overview of the three fundamental memory areas used by a program — <strong>the Stack, the Heap, </strong>and<strong> Static Memory.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gj0nQctmIgLb-fJLHdUO2A.png" /></figure><h4><strong>3.5 Static Memory</strong></h4><p>So far, we have examined two different memory regions. While the <strong>stack</strong> stores short-lived data created during function calls, the <strong>heap</strong> is used for dynamic objects whose lifetime is determined at runtime.</p><p>However, there is some data that is neither limited to the lifetime of a function nor created dynamically during execution. They exist from the moment the program starts and continue to exist until the program ends.</p><p>This type of data is stored in the <strong>Static Memory</strong> region.</p><p>For example, the variables in the code below remain in memory throughout the entire program:</p><pre>int GlobalCounter = 0;<br><br>void Foo()<br>{<br>  static int CallCount = 0;<br>  CallCount++;<br>}</pre><p>• GlobalCounter is created when the program starts and remains in memory until the program ends.</p><p>• CallCount, on the other hand, is accessible only from within the Foo() function, but it is not recreated each time the function is called. It is created on the first call and persists until the program terminates.</p><p>The most important feature of Static Memory is that <strong>its memory is automatically allocated and deallocated.</strong> The programmer does not use new, malloc, delete, or free for these variables. The operating system and the loader prepare this space when the program starts; when the program ends, they automatically clean it up.</p><p>For this reason, <strong>Static Memory</strong> is not within the scope of the Garbage Collector. This is because the lifetime of the data here is already the same as the program’s lifetime. There is no problem of deciding which data to delete and when.</p><p>In the next section, we’ll examine an interesting optimization technique. <strong>Escape</strong> Analysis analyzes whether certain objects actually need to be placed on the heap and, whenever possible, attempts to create them on the stack. This reduces memory usage and lightens the Garbage Collector’s workload.</p><h4><strong>3.6 Escape Analysis</strong></h4><p>So far, we’ve seen that objects can be created on the <strong>stack</strong> or the <strong>heap</strong>. However, modern compilers and runtimes don’t always leave this decision up to the programmer.</p><p><strong>Escape Analysis</strong> is an optimization technique that analyzes whether an object escapes the scope in which it was created. If an object is used only within the function where it was created and is not referenced externally, the compiler can create it on the <strong>Stack</strong> instead of the Heap.</p><p>For example, in the code below, the Point object is used only within the Foo() function:</p><pre>struct Point<br>{<br>  int x,y;<br>};<br><br>void Foo()<br>{<br>  Point p = {10,20};<br>}</pre><p>Since the lifetime of this object is limited to the function, some compilers or runtimes may create it directly on the Stack instead of placing it on the Heap. This way, no dynamic memory allocation occurs, and the number of objects the Garbage Collector must track is reduced.</p><p>Conversely, if a reference to an object extends beyond the function or if its lifetime cannot be precisely determined at compile time, it is created on the heap to ensure safety.</p><p>Escape analysis is a particularly important optimization technique in Go and JVM<strong>-based languages.</strong> In C++, however, whether an object is created on the stack or the heap is mostly determined by the programmer.</p><p>With this section, we have now seen how a program uses memory. In the next section, we will examine why memory management is a difficult problem and how issues such as <strong>memory leaks, dangling pointers, and double free arise.</strong>These problems are the most important factors that paved the way for the creation of the garbage collector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6QOLZPJeIqgprdePHgA4bQ.png" /></figure><h3><strong>4. Problems with Memory Management (Why Did We Need a Garbage Collector?)</strong></h3><p>In the previous section, we examined how programs use memory. We saw that memory regions such as the <strong>stack, heap, and static memory</strong> serve different purposes, and in particular, that the lifetime of objects created on the heap is determined at runtime.</p><p>However, this raises an important question: <strong>Who decides when memory allocated on the heap should be released?</strong></p><p>In languages that use manual memory management, this responsibility falls entirely on the programmer. If memory is not freed in a timely manner, it continues to be wasted; if it is freed too early, the program may access invalid addresses. Furthermore, even if memory is freed at the right time, it can become fragmented over time, or the same memory area may be accidentally freed multiple times.</p><p>Over the years, software developers have encountered performance issues, application crashes, and even serious security vulnerabilities due to such errors.</p><p>In this section, we will examine the primary memory management problems that led to the development of the garbage collector. Understanding these problems will lay the foundation for understanding why automatic memory management was developed and why modern programming languages use a garbage collector.</p><h4><strong>4.1 Memory Leak</strong></h4><p><strong>A memory leak</strong> occurs when memory that has been allocated is not released back to the system even though it is no longer needed. In other words, the program continues to allocate memory on the heap but does not free up the unused areas.</p><p>Let’s look at a simple example:</p><pre>int* numbers = new int[100];<br><br>// numbers is no longer used.<br>// However, memory was not released because delete was not called.</pre><p>In this example, even though the numbers array is no longer needed, the allocated memory continues to be used on the heap because delete[] was not called. If the program repeats this process over and over, the amount of unused memory increases over time.</p><p>A small memory leak often goes unnoticed at first. However, in applications that run for long periods, this can have serious consequences. Since web servers, game engines, or database systems can run for days or even months, every leak accumulates over time, increasing memory consumption. As a result, the application’s performance may decline, the operating system may be forced to allocate more memory, or the program may crash entirely.</p><p>The most important characteristic of a memory leak is that <strong>the memory is still allocated but no longer serves any purpose.</strong> This is one of the fundamental problems the Garbage Collector aims to solve. If an object can no longer be accessed from anywhere, the memory it occupies must be automatically reclaimed.</p><p>Of course, memory leaks do not disappear entirely even in languages that use a garbage collector. Objects that appear accessible due to improper reference management but are not actually in use may still remain in memory. We will return to this topic later in this chapter.</p><h4><strong>4.2 Dangling Pointer &amp; Use-After-Free</strong></h4><p>Errors in memory management are not limited to failing to free memory at all. Sometimes the opposite happens: a program frees a block of memory too early, even though it still needs it. In this case, a “<strong>dangling pointer</strong>” problem arises.</p><p>A dangling pointer is a pointer that continues to point to a memory address that is no longer valid. Even if the memory has been freed, the pointer’s value does not change and it continues to point to the old address.</p><p>Let’s examine the following example:</p><pre>int* value = new int(42);<br>delete value;<br><br>// value still points to an address,<br>// but this address is no longer valid.</pre><p>Continuing to use the value pointer from this point onward results in <strong>undefined behavior.</strong> This is because the program is attempting to access a memory block that no longer belongs to it.</p><p>This situation is called “<strong>Use-After-Free</strong>.” In other words, it involves attempting to reuse a memory area that has already been freed.</p><p>This code may sometimes appear to work correctly, sometimes produce random values, and sometimes cause the program to crash suddenly. This is because the freed memory may have been reused for another purpose by that time.</p><p>A “Use-After-Free” error does not merely lead to erratic behavior; it is also one of the most dangerous memory errors from a software security perspective. Attackers can cause the program to behave unexpectedly by filling freed memory areas with controlled data. For this reason, “Use-After-Free” errors lie at the root of many critical security vulnerabilities.</p><p>In languages that use a garbage collector, however, such errors are largely eliminated because the programmer does not free memory directly. An object is not removed from memory until the garbage collector determines that it is no longer in use.</p><p>In the next section, we will examine a different memory management error: the accidental freeing of the same memory area more than once — the “<strong>Double Free</strong>” problem.</p><h4><strong>4.3 Fragmentation (Memory Fragmentation)</strong></h4><p>Even if all objects are released at the right time in memory management, another problem may arise: <strong>fragmentation</strong>.</p><p>As the program runs, new memory blocks are continuously allocated on the heap, and old blocks are freed. Over time, these operations cause irregular gaps to form in memory.</p><p>For example, consider a heap like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5LY7KAO2UZxDUeEnqlhoQ.png" /></figure><p>Although there are a total of three units of free space here, these gaps are disconnected from one another. If the program requests a single contiguous memory block of three units, this request may not be fulfilled even though there is sufficient total free space.</p><p>This situation is called <strong>External Fragmentation.</strong></p><p>In addition, the wasted space that results when an allocated memory block is not fully utilized is referred to as <strong>Internal Fragmentation.</strong></p><p>Fragmentation is not a direct error; however, over time, it makes memory usage inefficient. The program may consume more RAM, memory allocations may slow down, and in some cases, new allocations may fail even though there is sufficient free memory.</p><p>Modern memory managers and some garbage collection algorithms attempt to reduce this fragmentation by reorganizing objects (compaction). We will revisit this topic in later sections when we examine garbage collection algorithms.</p><h4><strong>4.4 The Ownership Problem</strong></h4><p>At the root of many memory management problems lies a common question:</p><p><strong>Who is responsible for this object’s lifetime?</strong></p><p>In the software world, this question is referred to as “<strong>Ownership</strong>.”</p><p>Let’s consider a simple example. A function creates an object on the heap and passes it to another function.</p><pre>Player* player = new Player();</pre><p>So who will delete the player object?</p><p>• The function that created it?</p><p>• The function that uses it?</p><p>• Or some other component?</p><p>If the answer to this question isn’t clear, two different problems can arise. If no one deletes the object, a <strong>memory leak</strong>occurs. If multiple components attempt to delete it, errors such as <strong>dangling pointers</strong> or <strong>double free</strong> may occur.</p><p>Managing this responsibility correctly is quite challenging in large software projects. An object may be used by many different classes or modules over time, and tracking its lifetime becomes increasingly complex.</p><p>Different programming languages have developed different solutions to this problem. In C++, <strong>RAII</strong> and <strong>smart pointer</strong>constructs; in Rust, the <strong>ownership model</strong>; and in languages like Java and C#, the <strong>garbage collector </strong>largely take on this responsibility automatically.</p><p>Ultimately, the primary purpose of the garbage collector is not merely to clean up unused memory. Its main goal is to track the lifetimes of objects and delegate this responsibility from the programmer to runtime.</p><h4><strong>4.5 Memory Leaks in Languages with a Garbage Collector</strong></h4><p>A garbage collector automatically clears objects that are no longer in use from memory. However, <strong>this does not mean that memory leaks cannot occur in languages that use a garbage collector.</strong></p><p>The basic operating principle of a garbage collector is as follows: <strong>If an object is still reachable, it is assumed to be in use and is not deleted.</strong> However, even if an object is technically reachable, it may no longer serve any purpose from the application’s perspective.</p><p>For example, in Java or C#, objects added to a long-lived collection but never subsequently removed continue to reside in memory.</p><pre>List&lt;User&gt; users = new ArrayList&lt;&gt;();<br><br>users.add(new User());</pre><p>Similarly, unremoved <strong>event listeners</strong>, unnecessarily held <strong>static references</strong>, or misused <strong>ThreadLocal</strong> structures can also cause objects to remain reachable.</p><p>In such cases, the garbage collector works correctly because there is still a reference to the object. The problem is that the application continues to reference the object even though it is no longer actually needed.</p><p>Therefore, while the garbage collector greatly simplifies memory management, it does not replace proper reference management. The programmer is still responsible for cleaning up unnecessary references and properly designing the lifecycle of objects.</p><p>The problems we’ve seen throughout this section highlight why manual memory management is difficult and why automatic memory management is necessary. In the next section, we’ll examine the historical context of this need and <strong>see how the Garbage Collector came to be.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sL3K3GsyqCB7a9nDg_keCw.png" /></figure><h3><strong>5. The Birth of the Garbage Collector</strong></h3><p>In the previous section, we examined the problems associated with manual memory management. Issues such as <strong>memory leaks, dangling pointers, fragmentation</strong>, and <strong>ownership </strong>became increasingly complex as software evolved. Especially in large projects, keeping track of which objects should be deleted and when was both difficult and prone to errors.</p><p>So, couldn’t a different approach have been developed to solve this problem?</p><p>The <strong>garbage collector</strong> is precisely the answer to that question. The idea of delegating this responsibility to runtime — rather than having programmers manage the lifetime of each object individually — has gradually become one of the most important features of modern programming languages.</p><p>In this section, we will explore how the concept of the garbage collector emerged and how it has evolved over the years.</p><h4><strong>5.1 Before the Garbage Collector</strong></h4><p>In programs developed in the 1950s and 1960s, memory management was entirely the programmer’s responsibility. A program would allocate the memory it needed on its own and free it up when it was done. Since programs were relatively small, this approach sufficed for a long time.</p><p>However, as software grew, memory management became increasingly complex. While it was possible to track where an object was created, the real challenge was <strong>determining when it was no longer in use.</strong> Especially for objects shared by multiple functions or modules, managing their lifetimes correctly became a serious problem.</p><p>During this period, <strong>John McCarthy</strong> and his team, who were developing research for artificial intelligence, approached this problem from a different perspective. The <strong>LISP</strong> programming language developed by McCarthy performed symbolic computations that constantly created new data structures. In such applications, manually managing memory was both difficult and highly prone to errors.</p><p>Consequently, McCarthy proposed the idea that objects no longer in use should be automatically detected and cleaned up by the runtime, rather than by the programmer. This approach is considered one of the earliest examples of the mechanism we know today as <strong>Garbage Collection.</strong></p><p>Of course, the garbage collectors of that era were not as advanced as the ones we use today. However, the fundamental idea was the same: <strong>rather than making the programmer ask, “When should I delete this object?”, the system makes that decision.</strong></p><p>It was this idea that changed the perspective on memory management in the software world and inspired many programming languages in the years that followed.</p><h4><strong>5.2 The Evolution of the Garbage Collector</strong></h4><p>When the concept of the garbage collector first emerged, the primary goal was simply to clear unused objects from memory. However, as software grew and hardware advanced, this alone became insufficient.</p><p>Early garbage collectors performed memory scans by completely halting the program (<strong>Stop-The-World</strong>). While this approach was acceptable for small applications, it caused serious performance issues in large systems containing millions of objects.</p><p>Over time, different programming languages and runtimes developed new garbage collection algorithms tailored to their specific needs. While <strong>Smalltalk</strong> popularized the use of garbage collectors in object-oriented programming, <strong>Java</strong> and .<strong>NET</strong> made automatic memory management a part of daily life for millions of developers.</p><p>Today, however, the goal is no longer merely to free up unused memory. Modern garbage collectors must be able to operate with minimal disruption to the application, take advantage of multi-core processors, and keep latency to a minimum. For this reason, many different approaches have been developed, such as <strong>Concurrent, Parallel, Generational, G1, ZGC, </strong>and<strong> Shenandoah.</strong></p><p>Although all these systems work differently, their common goal is the same: <strong>to safely identify objects that are no longer in use and reclaim memory as efficiently as possible.</strong></p><p>In the next section, we’ll set aside the historical development and focus directly on this question:</p><p><strong>What exactly is a garbage collector, and what does it actually do?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WTItwgM-AU2o6B9fDEOig.png" /></figure><h3><strong>6. What Is a Garbage Collector?</strong></h3><p>So far, we’ve examined how memory works, why the heap was introduced, and the problems associated with manual memory management. All of this information leads us to a single point:</p><p><strong>The Garbage Collector.</strong></p><p>A Garbage Collector (GC) is a memory management mechanism that automatically reclaims the memory occupied by objects that are no longer in use during runtime.</p><p>The key point here is that the Garbage Collector does not clean up memory randomly. It must be certain that an object is truly no longer in use before it can be deleted. Otherwise, deleting an object that is still needed would cause the program to malfunction.</p><p>Therefore, the Garbage Collector’s primary task is not to free memory, but <strong>to determine which objects should continue to exist.</strong> Reclaiming memory is a natural consequence of this decision.</p><p>The Garbage Collector is an essential part of the runtime in many modern languages, such as Java, C#, Go, and JavaScript. Although each language uses different algorithms, the fundamental principle remains the same: to relieve the programmer of much of the burden of manual memory management and to enhance memory safety.</p><p>In this section, we will examine the responsibilities of the Garbage Collector. In the next section, we will see step by step how it makes these decisions — that is, how it determines which objects are “garbage.”</p><h4><strong>6.1 What Is a Garbage Collector?</strong></h4><p><strong>A Garbage Collector (GC)</strong> is a memory management mechanism that automatically reclaims the memory occupied by objects that are no longer in use at <strong>runtime</strong>.</p><p>The phrase “no longer in use” is quite important here. This is because the Garbage Collector does not look at an object’s value or how long it has been unused. Instead, it analyzes whether the program can still reach that object (<strong>reachability</strong>). If an object can no longer be accessed via any valid reference, the Garbage Collector marks it as “<strong>garbage</strong>.”</p><p>Thanks to this approach, in most cases, the programmer does not have to manually perform operations like `free` or `delete`. The runtime system decides when to reclaim memory.</p><p>However, the Garbage Collector’s job is not merely to clean up memory. First, it determines which objects should continue to exist, and then it reclaims memory only from objects that are truly unused. If an incorrect decision is made, an object that is still in use may be deleted, potentially compromising the program’s correctness. Therefore, the Garbage Collector’s most important task is <strong>to make the right decision.</strong></p><p>Today, the Garbage Collector is a standard feature in many modern languages such as <strong>Java, C#, Go, </strong>and<strong> JavaScript.</strong>Although the algorithms they use differ, they all aim to solve the same fundamental problem:<strong> safely identifying unused objects and automatically managing memory.</strong></p><p>In the next section, we’ll take a closer look at the Garbage Collector’s responsibilities and see<strong> what it manages — and what it doesn’t.</strong></p><h4><strong>6.2 What Does the Garbage Collector Do, and What Doesn’t It Do?</strong></h4><p>The garbage collector’s primary responsibility is to reclaim memory occupied by objects on the <strong>heap that are no longer accessible. Everything else falls outside the garbage collector’s scope</strong>.</p><p>For example, local variables on the <strong>stack</strong> are automatically removed when the function ends. This process is handled entirely by the processor and the runtime; the Garbage Collector does not intervene.</p><p>Similarly, global and static variables in the <strong>static memory</strong> region remain in memory for the duration of the program’s lifetime. The management of these areas is handled by the operating system and the runtime.</p><p>The Garbage Collector also does not manage <strong>file handles</strong>, <strong>network sockets</strong>, database connections, or other resources provided by the operating system. These resources are independent of memory and must be released by the program at the appropriate time.</p><p>In short, the Garbage Collector’s scope is limited to the <strong>memory of objects</strong>, not all system resources used by those objects.</p><p>Understanding this distinction is quite important. Even though memory management is automatic in a language that uses a Garbage Collector, properly managing the lifecycle of other system resources remains the programmer’s responsibility.</p><p>In the next section, we will examine <strong>when the Garbage Collector runs and who makes that decision.</strong> This will help us determine whether the GC is a continuously running mechanism or a system that activates under specific conditions.</p><h4><strong>6.3 When Does the Garbage Collector Run?</strong></h4><p>The garbage collector is not a mechanism that runs continuously. It is triggered by the <strong>runtime</strong> when certain conditions are met.</p><p>These conditions may vary depending on the programming language and the garbage collector algorithm. For example, the heap usage reaching a certain level, an increase in new memory allocations, or the runtime identifying an appropriate moment can trigger the garbage collector. In some languages, the programmer may request that the garbage collector run; however, the final decision still rests with the runtime.</p><p>When the Garbage Collector runs, it first determines which objects are still in use. It then identifies unreachable objects and reclaims the memory they occupy. Depending on the algorithm used, this process can be performed by completely halting the application (<strong>Stop-The-World</strong>) or <strong>concurrently</strong> while the application continues to run.</p><p>Just as important as when the Garbage Collector runs is how it operates, from a performance perspective. This is because a poorly designed Garbage Collector can lead to long wait times and performance losses.</p><p>For this reason, modern Garbage Collectors focus not only on finding the correct objects but <strong>also on doing so as quickly as possible</strong> <strong>with minimal latency.</strong></p><p>Now that we know what a garbage collector is, what its responsibilities are, and when it runs, in the next section we’ll move on to the most technical part of this article and seek the answer to the following question:</p><p><strong>How does the garbage collector determine that an object is truly unused?</strong></p><p>The answer to this question will introduce us to the fundamental concepts of modern garbage collection, such as the Root Set, Reachability<strong>, Object Graph, </strong>and<strong> Tri-Color Marking.</strong> Starting with this section, we’ll begin examining the internal architecture of the garbage collector step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxkMVhfcHF6UFCcQZBkvww.png" /></figure><h3><strong>7. How Does the Garbage Collector Work?</strong></h3><p>So far, we’ve examined why the Garbage Collector was created, what problem it solves, and its basic responsibilities. However, the most important question remains unanswered:</p><p><strong>How does the Garbage Collector know when an object is no longer in use?</strong></p><p>At first glance, this may seem like a very difficult problem. After all, there can be thousands, or even millions, of objects in memory at any given time. The Garbage Collector must correctly determine which of these objects are still in use and which are no longer needed.</p><p>To do this, the Garbage Collector does not scan memory randomly. Instead, it examines the program’s reference relationships to create a connection graph among objects and traverses this graph according to specific rules. In this way, it determines which objects are still accessible and which have become completely inaccessible.</p><p>Although the optimizations they use may differ, the vast majority of modern Garbage Collector algorithms share the same basic idea: <strong>First, find the live objects; then, clean up the rest.</strong></p><p>In this section, we will examine step by step how the garbage collector makes this decision. We will first introduce the concept of the <strong>root set</strong>, then discuss reference relationships between objects, marking algorithms, and the fundamental data structures used by modern garbage collectors.</p><h4><strong>7.1 Root Set &amp; Reachability</strong></h4><p>The garbage collector’s primary task is to determine which objects should remain in memory. However, to do this, it must first answer the following question:</p><p><strong>How can we tell if an object is still in use?</strong></p><p>The first idea that comes to mind might be to check all objects one by one. However, in an application with millions of objects, this approach is both slow and unreliable.</p><p>Instead, the Garbage Collector uses a much simpler principle:</p><p><strong>If an object is still reachable, it should remain in memory. If it is unreachable, it can be considered garbage.</strong></p><p>So where does this search begin?</p><p>This is where the concept of the <strong>Root Set</strong> comes into play.</p><p>The Root Set consists of all the starting points containing references that the program can definitely access at that moment. The Garbage Collector begins its scan from these points and determines which objects are reachable by following the references.</p><p>Although the contents of the Root Set may vary depending on the programming language and runtime, it generally consists of the following sources:</p><p>• Local variables in <strong>thread stacks</strong></p><p>• <strong>Static</strong> and <strong>global</strong> references</p><p>• References held in <strong>CPU registers</strong></p><p>For example, consider the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baTbwUoX3MOrRHt0r2Zn0A.png" /></figure><p>In this example, the Garbage Collector begins its scan from the <strong>Root</strong>.</p><p>• It can reach A from the Root.</p><p>• It can reach B and C through A.</p><p>• However, since there is no connection to <strong>Object D</strong>, it cannot reach it.</p><p>As a result, while <strong>A, B</strong>, and <strong>C</strong> remain in memory, <strong>D</strong> is considered an <strong>unreachable</strong> object and can be reclaimed by the Garbage Collector.</p><p>An important point to note here is that the Garbage Collector cannot know whether an object is being used or not. It only knows whether it is reachable. Therefore, if an unnecessary reference is held to an object, the Garbage Collector cannot delete it, even if it is never actually used.</p><p>This concept forms the foundation of modern Garbage Collector algorithms. However, it is not sufficient on its own. During this search, which begins with the Root Set, the relationships between objects must also be tracked.</p><p>In the next section, we will examine how these relationships form an <strong>Object Graph</strong> and how the Garbage Collector traverses this graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwD4SIUNWbnoSmyxuqsOTg.png" /></figure><h4><strong>7.2 Object Graph</strong></h4><p>In the previous section, we saw that the Garbage Collector tracks objects accessible starting from the <strong>Root Set</strong>. So how is this tracking performed?</p><p>The Garbage Collector does not view objects in memory as independent entities, but rather as nodes connected to one another through references. When all these connections are brought together, they form a structure called the Object Graph.</p><p>In this graph:</p><p>• Each <strong>object</strong> represents a node.</p><p>• A reference from one object to another represents a connection (<strong>edge</strong>) between two nodes.</p><p>For example, consider the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0j7nIE-WSyZq96fdYqQLQ.png" /></figure><p>In this example, the <strong>Player</strong> holds references to both the <strong>Inventory</strong> object and other objects. The Garbage Collector starts from the Root Set, traces these connections one by one, and marks all objects it can reach as <strong>live objects.</strong></p><p>Objects on the graph that cannot be reached via any connection are considered unreachable and can be removed from memory in a later stage.</p><p>So how does the Garbage Collector traverse this graph?</p><p>In computer science, the most common methods used for this are the <strong>Depth-First Search (DFS) </strong>and<strong> Breadth-First Search (BFS)</strong> algorithms. Both approaches reach the same objects; the difference lies in the order in which they visit the graph. Depending on the algorithm used by the Garbage Collector, one of these methods or a similar traversal technique may be preferred.</p><p>The Object Graph is one of the fundamental data structures of modern Garbage Collector algorithms. Mark-and-Sweep, Generational GC, and many other algorithms make their decisions based on scans performed on this reference graph.</p><p>In the next section, we will examine how objects are marked during this scan and explore the <strong>Tri-Color Marking</strong>algorithm, which forms the foundation of modern garbage collectors.</p><h4><strong>7.3 Tri-Color Marking</strong></h4><p>As the garbage collector traverses the object graph, it must not only visit objects but also track which objects are in which phase. To do this, most modern garbage collectors use the Tri-Color Marking model.</p><p>In this model, each object is in one of three different states:</p><p>• <strong>White</strong>: These are objects that have not yet been visited. Objects that remain white at the end of the scan are considered unreachable, and their memory can be reclaimed.</p><p>• <strong>Gray</strong>: The object has been discovered, but the other objects it references have not yet been examined.</p><p>• <strong>Black</strong>: The object has been fully examined. Both the object itself and all objects it references have been traversed.</p><p>The traversal process begins with the Root Set. Initially, all objects are considered white. Objects reached from the Root Set are marked as gray and processed in sequence. Once all objects referenced by a gray object have been discovered, that object is marked as black.</p><p>This process continues until there are no gray objects remaining.</p><p>The following example illustrates this transition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lQoz71OghJOLXX9RziVRQ.png" /></figure><p>Objects that remain <strong>white</strong> once the scan is complete are those that cannot be reached from the Root Set in any way. The Garbage Collector treats these objects as <strong>garbage</strong> and can reclaim their memory.</p><p>The most significant advantage of Tri-Color Marking is that it allows for clear tracking of an object’s collection status. Additionally, this model forms the basis for <strong>Concurrent Garbage Collector</strong> algorithms that perform memory collection while the application continues to run.</p><p>The <strong>Write Barrier</strong> and <strong>Read Barrier</strong> mechanisms, which we will discuss in the next section, were also developed to ensure that Tri-Color Marking functions correctly.</p><h4><strong>7.4 Concurrent Garbage Collection and Barrier Mechanisms</strong></h4><p>In the scanning process we’ve described so far, we’ve made an important assumption: We’ve assumed that the program’s memory remains unchanged while the garbage collector is running.</p><p>In reality, however, this is not the case. Modern applications may create new objects, modify existing references, or update connections between objects while they continue to run.</p><p>This creates a new problem for the garbage collector.</p><p>For example, suppose the garbage collector has started scanning an object. At that very moment, a running thread might add a new reference from that object to another object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qirt4AxdB-mcasdfM6kNRw.png" /></figure><p>If the garbage collector fails to detect this change, it may never visit object <strong>B.</strong> As a result, an object that is still in use may be mistakenly marked as garbage.</p><p>To solve this problem, modern garbage collectors use mechanisms called <strong>barriers</strong>.</p><p>One of the most commonly used methods is the <strong>Write Barrier.</strong> When a program modifies a reference, the Write Barrier notifies the Garbage Collector of this change. This ensures that the GC does not overlook new references created during the scan.</p><p>Some algorithms, on the other hand, use a <strong>Read Barrier</strong>. In this approach, specific checks are performed when an object is read, providing the Garbage Collector with the additional information it needs.</p><p>Thanks to barrier mechanisms, modern Garbage Collectors can perform memory sweeps <strong>concurrently</strong> without completely halting the application. This significantly reduces wait times, especially in large applications.</p><h4><strong>7.5 Stop-The-World (STW) and Safepoints</strong></h4><p>For the garbage collector to make accurate decisions, memory must remain as consistent as possible during the scan. However, while the application continues to run, objects may be created, references may be modified, or existing objects may be deleted. This situation can cause the garbage collector to produce incorrect results.</p><p>The simplest way to solve this problem is to pause the application briefly while the Garbage Collector is running. This approach is called <strong>Stop-The-World (STW).</strong></p><p>During STW, all threads in the application are temporarily paused. This allows the Garbage Collector to safely scan the memory without any changes and accurately determine which objects are accessible.</p><p>Most early Garbage Collector algorithms relied entirely on the Stop-The-World approach. However, as the heap size grew, the scanning time began to increase. This resulted in brief pauses (pause time) that users could perceive in the application.</p><p>Modern Garbage Collectors can perform a large portion of the memory scan while the application continues to run (concurrently) to reduce these pause times. Nevertheless, even many modern garbage collectors still require brief “Stop-The-World” pauses at certain stages. The goal is not to eliminate these pauses entirely, but to keep them as short as possible.</p><p>So, at exactly <strong>what moment</strong> are all threads in the application paused?</p><p>This is where the concept of a <strong>safepoint</strong> comes into play.</p><p>A safepoint is a specific execution point where a thread can be safely paused. The garbage collector does not pause threads in the middle of a random machine instruction. Instead, it waits for them to reach these safe points, which are predetermined by the runtime.</p><p>This allows the garbage collector to obtain consistent information about the threads’ state and perform the memory sweep safely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Br46r4q7EZKNmMJJRe_Tw.png" /></figure><h3><strong>8. Garbage Collection Algorithms</strong></h3><p>So far, we have learned the basic operating principle of the garbage collector. However, there is no single garbage collection algorithm. Over time, many approaches have been developed to address different needs.</p><p>While some algorithms aim to use less memory, others focus on minimizing application pauses as much as possible. Some prioritize simplicity, while others aim to deliver higher performance in large systems containing millions of objects.</p><p>Every algorithm has its advantages and disadvantages. For this reason, modern Garbage Collectors in use today often combine multiple techniques.</p><p>In this section, we will examine Garbage Collection algorithms in an order that closely follows their historical development. This will allow us to see more clearly which problem each algorithm was designed to solve and why the next algorithm became necessary.</p><h4><strong>8.1 Reference Counting</strong></h4><p>One of the oldest and most easily understandable approaches in the history of garbage collection is the <strong>Reference Counting</strong> algorithm.</p><p>The basic idea behind this algorithm is quite simple. Every object in memory carries a counter (<strong>reference count</strong>) that tracks how many different references point to it.</p><p>When a new reference to an object is created, the counter is <strong>incremented by one</strong>. When an existing reference is removed, the counter is <strong>decremented by one</strong>. If the counter drops to <strong>0</strong>, there are no longer any references that can access that object, and the object can be safely removed from memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5r7xPfmVpHmg4aszf0cRw.png" /></figure><p>The image above illustrates this process step by step. In the initial state, since only the <strong>Player</strong> references the Weapon object, the reference count is <strong>1</strong>. Later, when the Enemy also begins using the same object, the reference count becomes<strong> 2</strong>. When the Player’s reference is removed, the reference count drops back to <strong>1</strong>. Finally, when the Enemy’s reference is also removed, the reference count becomes <strong>0</strong>, and the Weapon object can be removed from memory.</p><p>The most significant advantage of Reference Counting is its ability to immediately clean up unused objects. It does not require a comprehensive memory scan, nor does it need to traverse the entire heap to determine which objects should be deleted. Therefore, the algorithm is quite fast and easy to implement.</p><p>However, this approach has a significant weakness: <strong>Circular Reference.</strong></p><p>When two or more objects reference each other, their reference counts may not drop to zero even if all other references in the outside world are removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ze6FbJmcq54nf2Q4C-DAPA.png" /></figure><p>In this example, Object A and Object B reference each other. Even if all other references in the program are removed, the <strong>reference count</strong> for both objects remains at <strong>1</strong>. As a result, these objects — which are actually no longer accessible — continue to occupy memory, causing a <strong>memory leak.</strong></p><p>This problem demonstrated that simply tracking the reference count is not sufficient. The garbage collector needed to check not only <strong>how many references existed</strong> but also whether the objects were actually <strong>reachable</strong>.</p><p>This need paved the way for the development of the <strong>Mark-and-Sweep</strong> algorithm, which we will examine in the next section.</p><h4><strong>8.2 Mark-and-Sweep</strong></h4><p>The biggest problem with the Reference Counting algorithm was that it could not detect <strong>circular references</strong>. As long as a group of objects continued to reference one another, they could not be removed from memory — even if they were no longer in use.</p><p>One of the most important approaches developed to solve this problem is the <strong>Mark-and-Sweep</strong> algorithm.</p><p>Unlike Reference Counting, Mark-and-Sweep does not concern itself with the number of references. Instead, it checks whether an object is <strong>accessible from the Root Set</strong>. If an object can be reached via any reference chain starting from the Root Set, that object remains alive. If it cannot be reached, it is considered <strong>garbage</strong>.</p><p>The Mark-and-Sweep algorithm consists of two basic phases.</p><p><strong>1. Mark (Marking)</strong></p><p>In the first phase, the garbage collector begins scanning from the Root Set. It marks all objects it can reach by following references. During this process, it traverses the objects and identifies all live objects.</p><p>No objects are deleted from memory during this phase. The sole purpose is to determine which objects will remain in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PIgalxl3hPTCQ8NXpH-Q2Q.png" /></figure><p><strong>2. Sweep (Cleaning)</strong></p><p>Once the marking phase is complete, the Garbage Collector traverses the Heap once more.</p><p>This time, all unmarked objects are considered <strong>unreachable</strong>, and the memory they occupy is reclaimed.</p><p>Marked objects, however, remain in place, and the program continues to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odOSQGYOWOZtT8_rwRDWHw.png" /></figure><p>This approach naturally resolves the <strong>Circular Reference</strong> problem as well. This is because two objects that reference each other cannot be marked if they are unreachable from the Root Set. Consequently, both can be safely removed from memory during the Sweep phase.</p><p>Mark-and-Sweep forms the foundation of modern garbage collector algorithms. Although many garbage collectors used today incorporate various optimizations, they still rely on the core principle of this algorithm: <strong>first identify the live objects, then clean up the rest.</strong></p><p>However, Mark-and-Sweep also has a significant drawback.</p><p>The gaps left by objects removed from memory can, over time, create an irregular structure within the heap. This condition is called <strong>memory fragmentation</strong> and can make it difficult to allocate large memory blocks.</p><p>The algorithm developed to solve this problem is the <strong>Mark-and-Compact</strong> approach, which we will examine in the next section.</p><h4><strong>8.3 Mark-and-Compact</strong></h4><p>The <strong>Mark-and-Sweep</strong> algorithm we saw in the previous section was able to successfully clean up unreachable objects. However, it left behind a new problem.</p><p>The locations of objects removed from memory remained empty, and over time, irregular gaps formed within the heap. This situation is called <strong>Memory Fragmentation.</strong></p><p>For example, the following structure might form in memory:</p><p>[A] [ ] [B] [ ] [ ] [C] [ ]</p><p>Even if there is sufficient total free space, it may not be possible to place a large object because these gaps are disconnected from one another.</p><p>The <strong>Mark-and-Compact</strong> algorithm was developed to solve this problem.</p><p>The algorithm again begins with two basic steps. In the first phase, as in <strong>Mark-and-Sweep</strong>, live (<strong>reachable</strong>) objects are marked. However, in the second phase, not only are garbage objects cleaned up, but the remaining live objects are also moved together (<strong>compacted</strong>) to eliminate the gaps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILWGQa-0gGDClDbea21wAg.png" /></figure><p>As a result of this process, the heap becomes more organized.</p><p>Before</p><p>[A] [ ] [B] [ ] [ ] [C] [ ]</p><p>After</p><p>[A] [B] [C] [ ] [ ] [ ] [ ]</p><p>This approach makes it easier to allocate large memory blocks and prevents the heap from becoming fragmented over time.</p><p>Of course, this comes at a cost. Since objects are moved in memory, all references pointing to them must be updated to their new addresses. This process incurs additional time and CPU overhead.</p><p>Therefore, Mark-and-Compact is an algorithm that accepts the need for <strong>more processing</strong> in order to solve the fragmentation problem.</p><h4><strong>8.4 Modern Garbage Collector Approaches</strong></h4><p>Garbage collection technology has evolved significantly over the years. Garbage collectors used today generally do not rely on a single algorithm. Instead, they aim to achieve higher performance and lower latency by combining the strengths of different algorithms.</p><p>The primary goal of this development is to strike a balance among three key factors:</p><p>• <strong>Throughput</strong>: Ensuring the application can perform as much work as possible.</p><p>• <strong>Latency</strong>: Minimizing wait times during garbage collection.</p><p>• <strong>Memory</strong> <strong>Footprint</strong>: Ensuring efficient use of memory.</p><p>Various approaches have been developed to achieve these goals.</p><p><strong>Parallel Garbage Collection</strong></p><p>Early garbage collectors performed memory scanning on a single thread. Developed to take advantage of the multi-core architecture of modern processors, Parallel GC aims to complete the marking and sweeping processes more quickly by distributing them across multiple threads.</p><p><strong>Concurrent Garbage Collection</strong></p><p>Concurrent GC performs the majority of the memory scan while the application continues to run, rather than pausing the application for an extended period. This significantly reduces the wait times perceived by the user. However, this approach requires additional mechanisms, such as Write Barriers and Read Barriers, which we examined in the previous section.</p><p><strong>Incremental Garbage Collection</strong></p><p>Some garbage collectors divide the process into smaller chunks rather than scanning the entire heap at once. This approach is called Incremental GC. The goal is to create short, frequent garbage collection cycles rather than long pauses.</p><p>Today, modern systems such as <strong>G1</strong> and <strong>ZGC</strong> in Java, <strong>CLR GC</strong> in the .NET runtime, and the garbage collector in the Go runtime combine <strong>Mark-and-Sweep</strong>, <strong>Compaction</strong>, <strong>Generational</strong>, and <strong>Concurrent</strong> techniques depending on the workload.</p><p>In short, there is no single “best garbage collector algorithm” today. Each <strong>runtime</strong> strives to strike the optimal balance between performance, memory usage, and latency by combining strategies suited to its specific use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FkMTzJRa9OjUE1ogaaYiQ.png" /></figure><h3><strong>9. Garbage Collector Performance and Optimization</strong></h3><p>The primary purpose of the garbage collector is to automate memory management. However, this automation comes at a cost. Scanning memory, marking objects, moving them, and cleaning them up consumes processor time and can directly impact application performance.</p><p>For this reason, modern garbage collectors focus not only on functioning correctly but also on operating <strong>as quickly, efficiently</strong>, and <strong>transparently</strong> as possible — to the point where users do not notice them.</p><p>An application’s garbage collection performance can be influenced not only by the algorithm used but also by the structure of the code, memory usage patterns, and even hardware characteristics.</p><p>In this section, we will examine the key factors that determine garbage collector performance and the optimization techniques developers can implement.</p><h4><strong>9.1 Hardware Effects: CPU Cache and Cache Misses</strong></h4><p>A garbage collector is influenced not only by the algorithms it uses but also by the hardware on which it runs. Modern processors use small, high-speed memory units called <strong>CPU</strong> <strong>caches</strong> to access data as quickly as possible.</p><p>If objects in memory are located close to one another, the processor can quickly access this data via the cache. However, if objects are scattered throughout the heap, the Garbage Collector is forced to constantly access different memory regions while following references. This situation is called “<strong>pointer chasing</strong>.”</p><p>As pointer chasing increases, the data the processor needs may not be found in the cache. In such cases, the processor is forced to access RAM, which results in a <strong>cache miss.</strong> An increase in the number of cache misses can negatively impact garbage collection time and, consequently, the application’s overall performance.</p><p>For this reason, modern garbage collectors strive not only to find the correct objects but also to make memory accesses as <strong>cache-friendly</strong> as possible.</p><h4><strong>9.2 Writing GC-Friendly Code</strong></h4><p>Although the garbage collector handles memory management automatically, the structure of the code you write directly affects garbage collection performance. Creating too many unnecessary objects or producing short-lived objects can cause the garbage collector to run more frequently.</p><p>Therefore, in modern applications, the goal is not only to write correct code but also to write <strong>GC-friendly code.</strong></p><p>Here are some key points to keep in mind:</p><p>• <strong>Avoid creating unnecessary objects</strong>. Reuse existing objects as much as possible instead of constantly creating new ones.</p><p>• <strong>Use object pooling</strong>. Keeping objects that are frequently created and destroyed in a pool for reuse is particularly beneficial in areas where performance is critical, such as game development.</p><p>• <strong>Practice buffer reuse</strong>. Reusing existing memory blocks instead of constantly creating new arrays or buffers reduces the load on the heap.</p><p>• <strong>Prefer value types or structs</strong>. Using value types where appropriate can reduce allocations to the heap, thereby lightening the Garbage Collector’s workload.</p><p>While these recommendations may not apply equally to every language, the common goal remains the same: <strong>to reduce the Garbage Collector’s workload</strong>. Fewer allocated objects mean fewer memory sweeps and better performance.</p><p><strong>9.3 Profiling and Analysis Tools</strong></p><p>The first step in improving Garbage Collector performance is to properly analyze the application’s memory usage. It is often impossible to identify performance issues by examining the code alone. For this reason, <strong>profiling</strong> tools are of great importance.</p><p>There are many analysis tools developed for different platforms and runtimes. For example, <strong>JProfiler</strong> and <strong>VisualVM</strong> are widely used for JVM-based applications; <strong>dotMemory</strong> for .NET applications; <strong>pprof</strong> for Go projects; <strong>Chrome</strong> <strong>DevTools</strong>for JavaScript applications; and <strong>Unreal</strong> <strong>Insights</strong> for <strong>Unreal</strong> <strong>Engine</strong> projects to analyze memory usage and garbage collection behavior.</p><p>These tools allow for a detailed examination of memory allocations, garbage collection frequency, memory leaks, and performance bottlenecks. As a result, optimization decisions are based on real data rather than guesswork.</p><p>The most important principle in performance optimization is this:</p><p><strong>You cannot optimize a problem you haven’t measured.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isI8q9aiMp9oJo2-ztd2iQ.png" /></figure><h3><strong>10. Garbage Collection and the Runtime in Programming Languages</strong></h3><p>So far, we’ve examined how the garbage collector works and which algorithms it uses. However, these mechanisms do not operate on their own. When the garbage collector is triggered, which objects are tracked, and how memory is managed are largely determined by the <strong>runtime</strong> in which the program runs.</p><p>Since every programming language has different needs, they adopt different approaches to memory management. While some languages leave memory management entirely up to the developer, others use a garbage collector, and still others implement different <strong>ownership</strong> models.</p><p>Therefore, there is no single “correct” approach to memory management. Each method aims to strike a different balance between performance, security, and ease of use.</p><p>In this section, we will compare the memory management approaches of common programming languages and their relationship with garbage collectors.</p><h4><strong>10.1 The Role of the Runtime</strong></h4><p>When a program begins to run after being compiled, it does not communicate directly with the operating system. In most modern languages, there is a layer between the program and the operating system called the runtime.</p><p>The runtime ensures the program runs by handling memory allocation, running the garbage collector, managing threads, handling exceptions, and performing many other low-level tasks — all while hiding these details from the developer.</p><p>For example, Java applications run on the <strong>Java Virtual Machine (JVM)</strong>, while C# applications run on the <strong>Common Language Runtime (CLR).</strong> Go has its own runtime, and JavaScript engines also come with their own runtime components.</p><p>In contrast, languages such as C and C++ do not have a comprehensive runtime. Memory management is largely the developer’s responsibility, and operations such as `new`, `delete`, `malloc`, and `free` are controlled directly by the program.</p><p>This is why the same garbage collection algorithm can behave differently across different languages. This is because the component that implements and manages the algorithm is the language’s runtime architecture.</p><h4><strong>10.2 Memory Management in Different Languages</strong></h4><p>So far, we’ve learned how the garbage collector works and what problems different algorithms solve. So how is the same memory management problem addressed in different programming languages?</p><p>To see the answer to this question more clearly, we’ll use the same scenario across all languages.In each example, we’ll create a simple `Player` object and then remove the last reference to that object. The main point we’ll examine isn’t the creation of the object, but rather what happens in memory after the reference is removed.</p><p>In some languages, the developer must manually free the memory, while others leave this to the <strong>runtime</strong> or the garbage collector. Still others adopt a completely different approach, ensuring memory safety through <strong>ownership</strong> rules.</p><p>The examples below demonstrate how the same operation is performed in different languages and which mechanism manages memory.</p><h4><strong>C</strong></h4><p>In the C language, memory management is entirely the developer’s responsibility. Allocated memory must be manually released using `free()` once it is no longer needed.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br><br>typedef struct<br>{<br>    int health;<br>} Player;<br><br>int main()<br>{<br>    Player* player = (Player*)malloc(sizeof(Player));<br>    player-&gt;health = 100;<br><br>    printf(&quot;Health: %d\n&quot;, player-&gt;health);<br><br>    free(player);<br><br>    return 0;<br>}</pre><p>→Memory is allocated using malloc() and deallocated using free().</p><p><strong>Who Manages Memory?</strong></p><p>→The developer</p><h4><strong>C++</strong></h4><pre>#include &lt;iostream&gt;<br><br>class Player<br>{<br>public:<br>    int Health = 100;<br>};<br><br>int main()<br>{<br>    Player* player = new Player();<br><br>    std::cout &lt;&lt; player-&gt;Health &lt;&lt; std::endl;<br><br>    delete player;<br><br>    return 0;<br>}</pre><p>→If you forget to delete it, a memory leak may occur.</p><p><strong>Who Manages Memory?</strong></p><p>→The developer</p><h4><strong>C++ (Modern)</strong></h4><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class Player<br>{<br>public:<br>    int Health = 100;<br>};<br><br>int main()<br>{<br>    auto player = std::make_unique&lt;Player&gt;();<br><br>    std::cout &lt;&lt; player-&gt;Health &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><p>→When the scope ends, the memory is automatically released.</p><p><strong>Who Manages the Memory?</strong></p><p>→std::unique_ptr</p><h4><strong>Rust</strong></h4><pre>struct Player {<br>    health: i32,<br>}<br><br>fn main() {<br>    let player = Player { health: 100 };<br><br>    println!(&quot;{}&quot;, player.health);<br>}</pre><p>→When the scope ends, Drop runs automatically.</p><p><strong>Who Manages Memory?</strong></p><p>→Ownership + Borrow Checker</p><h4><strong>Swift</strong></h4><pre>class Player {<br>    var health = 100<br>}<br><br>var player: Player? = Player()<br><br>print(player!.health)<br><br>player = nil</pre><p>→When the reference count reaches zero, ARC frees the object.</p><p><strong>Who Manages Memory?</strong></p><p>→ARC</p><h4><strong>Java</strong></h4><pre>class Player {<br>    int health = 100;<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br><br>        Player player = new Player();<br><br>        System.out.println(player.health);<br><br>        player = null;<br>    }<br>}</pre><p>→The object is not immediately deleted; the garbage collector runs when the JVM deems it appropriate.</p><p><strong>Who Manages Memory?</strong></p><p>→The JVM Garbage Collector</p><h4><strong>Python</strong></h4><pre>class Player:<br>    def __init__(self):<br>        self.health = 100<br><br><br>player = Player()<br><br>print(player.health)<br><br>player = None</pre><p>→Once the reference is removed, the object is properly freed from memory.</p><p><strong>Who Manages Memory?</strong></p><p>→Reference Counting + Cyclic GC</p><h4><strong>JavaScript</strong></h4><pre>class Player {<br>    constructor() {<br>        this.health = 100;<br>    }<br>}<br><br>let player = new Player();<br><br>console.log(player.health);<br><br>player = null;</pre><p>→V8 cleans up unreachable objects at the appropriate time using the garbage collector.</p><p><strong>Who Manages Memory?</strong></p><p>→The V8 Garbage Collector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1f96rrNjElAc1nVaWuiaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aEQpjwiKgZQBn7c5FIQ4hw.png" /></figure><h3><strong>11. Garbage Collector Myths and Misconceptions</strong></h3><p>There are many misconceptions about the Garbage Collector that have been accepted as true for years. These misconceptions stem from incomplete or incorrect understandings of how the Garbage Collector works.</p><p>In this section, we will evaluate the most common myths in light of what we have learned so far.</p><h4><strong>11.1 “The Garbage Collector completely solves the memory leak problem.”</strong></h4><p><strong>False.</strong></p><p>The Garbage Collector can only clean up unreachable objects. If an object is still reachable, the Garbage Collector cannot delete it.</p><p>For example, objects forgotten in long-lived collections, static references, or unclosed event listeners remain in memory because they are still accessible. As a result, memory leaks can still occur in applications that use the Garbage Collector.</p><h4><strong>11.2 “Languages with a Garbage Collector are always slower.”</strong></h4><p><strong>False.</strong></p><p>Although the Garbage Collector incurs a certain processing cost, modern Garbage Collectors are highly advanced. Thanks to parallel, concurrent, and incremental techniques, pause times have been significantly reduced.</p><p>Furthermore, errors in manual memory management, incorrect optimizations, and memory fragmentation can also lead to significant performance losses. Therefore, performance should be evaluated not solely based on the presence of a garbage collector, but on the application’s overall design.</p><h4><strong>11.3 “Reference Counting is not a form of garbage collection.”</strong></h4><p><strong>False.</strong></p><p>Reference Counting is a form of garbage collection. However, unlike other tracing-based algorithms, it tracks reference counts rather than scanning objects.</p><p>Although it cannot solve the cyclic reference problem on its own, it is still actively used today in systems such as Automatic Reference Counting (ARC).</p><h4><strong>11.4 “When the garbage collector runs, all RAM is cleared.”</strong></h4><p><strong>False.</strong></p><p>The garbage collector’s job is not to completely clear memory. It only reclaims the space used by objects that are no longer accessible.</p><p>Live objects remain in memory, and many garbage collectors may retain the reclaimed memory for their own use for future allocations rather than immediately returning it to the operating system. Therefore, the application’s RAM usage may not always decrease noticeably after the garbage collector runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgoYdpkyTK7SjpX7agoyuQ.png" /></figure><h3><strong>12. Conclusion</strong></h3><p>The Garbage Collector is often defined simply as “a mechanism that deletes unused objects.” However, as we’ve seen throughout this article, the Garbage Collector is much more than that.</p><p>Starting with the physical structure of memory, we examined how processes use memory, the roles of the Stack and Heap, the problems associated with manual memory management, and how these problems paved the way for the emergence of the Garbage Collector. We then discussed the working principles of the Garbage Collector, the basic algorithms it uses, and how different programming languages solve this problem today.</p><p>This journey reveals an important truth: the Garbage Collector is not a standalone component. The operating system, hardware, compiler, runtime, and programming language all work together to make memory management possible. The Garbage Collector is merely one part of this larger system.</p><p>Another important point is that no memory management approach is flawless. While manual memory management gives the developer full control, it increases the risk of errors. The Garbage Collector simplifies the development process but comes with a certain performance cost. The ownership model, on the other hand, approaches memory safety from a different perspective. Which approach is more suitable depends entirely on the needs of the application being developed.</p><p>I hope this article has helped you see the Garbage Collector not just as a “background cleanup system,” but as an important part of a broad ecosystem that spans from hardware to runtime.</p><p>Technologies may change, algorithms may evolve, and new runtimes may emerge. However, the fundamental principles of memory management remain largely the same. Understanding these principles makes it easier not only to grasp the Garbage Collector but also to develop more efficient, secure, and high-performance software.</p><p>This article was prepared with the aim of creating a comprehensive and accessible reference resource on the Garbage Collector in Turkish. As new algorithms, runtimes, and technologies emerge over time, this guide will continue to be updated.</p><p>Thank you for reading.</p><h4><strong>References and Further Reading</strong></h4><p>This article was prepared based on the fundamental principles of memory management in the computer science literature, academic studies, and the official documentation of programming languages. The following resources are recommended for readers who wish to explore the topic in greater depth.</p><h4><strong>Official Documentation</strong></h4><p>• Java Virtual Machine (JVM) Documentation</p><p>• Oracle Java Garbage Collection Tuning Guide</p><p>• Microsoft .NET Garbage Collection Documentation</p><p>• Go Runtime &amp; Garbage Collector Documentation</p><p>• CPython Garbage Collector Documentation</p><p>• V8 JavaScript Engine Documentation</p><p>• Swift Automatic Reference Counting (ARC) Documentation</p><p>• Rust Ownership Documentation</p><p>• C++ Smart Pointer Documentation (cppreference)</p><h4><strong>Books</strong></h4><p>• Richard Jones, Antony Hosking, Eliot Moss — The Garbage Collection Handbook: The Art of Automatic Memory Management</p><p>• Robert Nystrom — Game Programming Patterns</p><p>• Scott Meyers — Effective Modern C++</p><p>• Bjarne Stroustrup — The C++ Programming Language</p><p>• Andrew S. Tanenbaum — Modern Operating Systems</p><p>• David A. Patterson &amp; John L. Hennessy — Computer Organization and Design</p><h4><strong>Academic Papers</strong></h4><p>• John McCarthy — Recursive Functions of Symbolic Expressions and Their Computation by Machine (1960)</p><p>• Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten, E. F. M. Steffens — On-the-Fly Garbage Collection: An Exercise in Cooperation (1978)</p><h4><strong>Recommended Topics</strong></h4><p>As a follow-up to this article, the following topics can be explored:</p><p>• Memory Allocator Designs (jemalloc, tcmalloc, mimalloc)</p><p>• JVM Garbage Collectors (G1, ZGC, Shenandoah)</p><p>• .NET CLR Garbage Collector</p><p>• Go Concurrent Garbage Collector</p><p>• V8 Orinoco Garbage Collector</p><p>• Rust Ownership and Borrow Checker</p><p>• CPU Cache, NUMA, and Memory Locality</p><p>• Lock-Free Memory Reclamation (Hazard Pointers, Epoch-Based Reclamation)</p><p>• Region-Based Memory Management</p><p>• Escape Analysis and Compiler Optimizations</p><p><strong>Note</strong>: Garbage collection is a constantly evolving field of research. New algorithms, low-latency runtime systems, and hardware-accelerated optimizations continue to advance every year. Therefore, consulting the official documentation for the relevant languages and runtimes is always the best approach to stay up to date.</p><p>“If you found this post helpful and would like to see more content like this, you can follow me on Medium and share your thoughts in the comments.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5915bd9cabd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>