<?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 Murat on Medium]]></title>
        <description><![CDATA[Stories by Murat on Medium]]></description>
        <link>https://medium.com/@muratakkan?source=rss-655192aecf6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dvA7-Mc7lLjh8TSn</url>
            <title>Stories by Murat on Medium</title>
            <link>https://medium.com/@muratakkan?source=rss-655192aecf6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:43:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muratakkan/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[Decoding the Debate: Interpreted vs. Compiled Programming Languages]]></title>
            <link>https://muratakkan.medium.com/decoding-the-debate-interpreted-vs-compiled-programming-languages-b5551c2f0770?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5551c2f0770</guid>
            <category><![CDATA[compiled-language]]></category>
            <category><![CDATA[compiled-vs-interpreted]]></category>
            <category><![CDATA[interpreted-languages]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 10:58:44 GMT</pubDate>
            <atom:updated>2023-08-09T11:04:09.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*kRZUbBSKMBi73CXU7UlAnw.jpeg" /></figure><h3><strong>Understanding the Basics</strong></h3><p>Before diving into the comparison, let’s establish what interpreted and compiled languages actually are:</p><ul><li>Interpreted Languages: These languages are executed line by line, with the program being translated and executed simultaneously. Python, Ruby, and JavaScript are classic examples. They offer flexibility and faster development but might sacrifice some performance due to runtime translation.</li><li>Compiled Languages: In contrast, compiled languages are transformed entirely into machine code or an intermediate representation before execution. C++, Java, and Go fall into this category. While they generally provide faster execution speeds, the compilation process might require more time upfront.</li></ul><blockquote>The main goal of both compilation and interpretation is to transform the human-readable source code into machine code that can be executed directly by a CPU, but there are some caveats to it.</blockquote><figure><img alt="Pros and cons Interpreted and. Compiled Programming Languages" src="https://cdn-images-1.medium.com/max/500/1*TC0LWxRjY2AYPai2zDPHgw.png" /></figure><p><strong>Interpreted Languages:</strong></p><p><em>Pros:</em></p><ul><li><em>Rapid Development</em>: Interpreted languages often have shorter feedback loops, allowing developers to quickly iterate and test their code.</li><li><em>Portability</em>: Since interpreters exist for multiple platforms, code written in interpreted languages can be easily shared and run on different systems.</li><li><em>Dynamic Typing</em>: Interpreted languages often employ dynamic typing, offering more flexibility when dealing with variable types.</li></ul><p><em>Cons:</em></p><ul><li>Performance Overhead: Running code through an interpreter can introduce performance bottlenecks compared to natively compiled languages.</li><li>Deployment Challenges: Distributing interpreted language programs can sometimes involve shipping the interpreter itself, making deployment more complex.</li></ul><p><strong>Compiled Languages:</strong></p><p><em>Pros:</em></p><ul><li><em>Optimized Performance:</em> Compiled languages often yield faster execution times due to the code being transformed into machine code optimized for the target system.</li><li><em>Early Detection of Errors</em>: Compilation can catch errors before runtime, leading to more stable and reliable software.</li><li><em>Security:</em> Compiled code can be more challenging to reverse-engineer, offering an added layer of security.</li></ul><p><em>Cons:</em></p><ul><li><em>Slower Development Cycle</em>: Compilation can be time-consuming, especially for larger projects, potentially slowing down the development process.</li></ul><blockquote>Interpreted languages were once significantly slower than compiled languages. But, with the development of <a href="https://guide.freecodecamp.org/computer-science/just-in-time-compilation">just-in-time compilation</a>, that gap is shrinking.</blockquote><ul><li><em>Platform Dependency</em>: Compiled binaries might not run on different platforms without recompilation.</li></ul><h3>Conclusion</h3><p>In the end, the choice between interpreted and compiled programming languages isn’t about one being definitively better than the other. It’s about finding the right tool for the job at hand. Each approach has its own advantages and drawbacks, and understanding these nuances is crucial for making informed decisions as a programmer. So, whether you’re team interpreted or team compiled, both sides contribute to the dynamic and diverse world of coding, shaping the landscape of technology one line of code at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5551c2f0770" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing String, StringBuffer, and StringBuilder in Java]]></title>
            <link>https://muratakkan.medium.com/comparing-string-stringbuffer-and-stringbuilder-in-java-128a08ff2a5f?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/128a08ff2a5f</guid>
            <category><![CDATA[string-builder]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[stringbuffer]]></category>
            <category><![CDATA[mutability]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 10:33:36 GMT</pubDate>
            <atom:updated>2023-01-14T10:35:59.978Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the Differences and When to Use Each</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*OwMTPWDLeSZu4pNFUCwXvg.png" /></figure><p>In Java, the String class is implemented as an object that has an internal char array. As arrays are immutable, meaning they cannot be expanded or changed, Strings are also immutable. This means that any modification to a String results in the creation of a new String object.</p><blockquote>If you want to understand mutable and immutable objects before dive into this, you can read my previous <a href="https://muratakkan.medium.com/understanding-mutability-in-java-5083b05327cc">post about mutability.</a></blockquote><p>To overcome this limitation, Java provides additional classes like StringBuffer and StringBuilder.</p><p>In this article, we will be exploring the distinctions between these three classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*w_5x3stYzWJYtLP3vYyLSw.png" /></figure><p>The main difference in performance between StringBuffer and StringBuilder is that StringBuilder is generally faster than StringBuffer.</p><p>The reason for this is that StringBuffer is thread-safe (synchronized) while StringBuilder is not. This means that StringBuffer has the overhead of synchronization, which can slow down its performance. StringBuilder, on the other hand, does not have this overhead, which makes it faster.</p><p>Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87f797a666e21d84b48539d03b66095d/href">https://medium.com/media/87f797a666e21d84b48539d03b66095d/href</a></iframe><p>Output:</p><p>Time taken by StringBuffer: 10ms<br>Time taken by StringBuilder: 3ms</p><p>In the above benchmark , both StringBuffer and StringBuilder are used to create a string of numbers from 0 to 100,000, the time taken by StringBuilder is less than the time taken by StringBuffer, because StringBuffer is thread-safe and has the overhead of synchronization.</p><p>It is worth noting that the performance difference between StringBuffer and StringBuilder can vary depending on the specific use case and the size of the input. However, in general, if performance is a primary concern and you are working in a single-threaded environment, it is recommended to use StringBuilder instead of StringBuffer.</p><blockquote>It is also worth mentioning that since Java 5, the recommended way of using StringBuilder instead of StringBuffer, except in the case where the thread-safety is required.</blockquote><h3>Summary</h3><p>String, StringBuffer and StringBuilder are all classes in Java that are used to represent and manipulate strings of characters. However, they have some key differences:</p><ol><li>String is an immutable class, meaning that once a string object is created, its value cannot be changed. Any operation that appears to change the value of a string object actually creates a new string object with the desired value.</li><li>StringBuffer is also a thread-safe (synchronized) version of StringBuilder. It means multiple threads can work on StringBuffer without any issue.</li><li>StringBuilder is similar to StringBuffer, but it is not thread-safe. This means that if multiple threads are working on a StringBuilder object at the same time, there is a possibility of data corruption.If you are working in a single-threaded environment, use StringBuilder, because it is more efficient.</li></ol><h3>So, which type of object should you use? It really depends on your needs.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=128a08ff2a5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BigDecimal: Achieving Financial Accuracy in Java]]></title>
            <link>https://muratakkan.medium.com/bigdecimal-achieving-financial-accuracy-in-java-76140af086bc?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/76140af086bc</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[double]]></category>
            <category><![CDATA[bigdecimal]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 20:31:43 GMT</pubDate>
            <atom:updated>2023-01-13T07:50:51.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*jrLqJuMsLY_5hd80rumlYg.png" /></figure><p>When working with numerical data in programming, it’s important to choose the appropriate data type to represent that data. Java provides several options for working with numerical data, including the double and BigDecimal data types.</p><p>While both data types can be used to represent decimal numbers, they have distinct differences and are suited for different use cases.</p><p>The double data type is a double-precision 64-bit IEEE 754 floating point, which means it has 15–17 significant digits of precision. It is often used for scientific and engineering calculations, as well as in financial applications where a high degree of precision is not required.</p><p>However, the double data type can lead to unexpected results when used in financial calculations due to the way it handles decimal values. Because of the way that floating-point arithmetic works, some decimal values cannot be represented exactly using a double, leading to small inaccuracies.</p><h3>0.1 + 0.2 NOT EQUAL TO 0.3!</h3><p>For example, in Java, 0.1 and 0.2 are represented as double values. However, these values cannot be represented exactly as a binary fraction, which is the way that floating-point numbers are represented in a computer’s memory. Therefore, the values of 0.1 and 0.2 are <strong>approximations of the actual decimal value</strong>.</p><p>When you add 0.1 and 0.2 together, <strong>you are adding these approximated values</strong>, which results in an approximation of the expected sum, 0.3. In most cases, this approximation is so close to the actual value that the difference is not noticeable.</p><p>However, in some cases, the approximation can lead to unexpected results. For example, the following code snippet:</p><pre>double num1 = 0.1;<br>double num2 = 0.2;<br>double sum= num1+num2;<br>if (sum == 0.3) {<br>    System.out.println(&quot;Equal result is: &quot;+sum);<br>} else {<br>    System.out.println(&quot;Not Equal result is: &quot;+sum);<br>}</pre><h4>Will output “Not Equal result is: 0.30000000000000004”</h4><p>Because the approximation of the sum of 0.1 and 0.2 is not exactly equal to 0.3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*dogXSIy8kPp-Az9s4QS9ng.png" /></figure><p>The BigDecimal class, on the other hand, is a more suitable choice for financial and monetary calculations. It provides arbitrary-precision decimal arithmetic, meaning it can represent decimal values exactly without the inaccuracies that can occur with double.</p><p>For example, consider the following code snippet where we are trying to calculate the total price of an item:</p><pre>BigDecimal num1 = new BigDecimal(&quot;0.1&quot;);<br>BigDecimal num2 = new BigDecimal(&quot;0.2&quot;);<br>BigDecimal sum= num1.add(num2);<br>if (sum.equals(new BigDecimal(&quot;0.3&quot;))) {<br>    System.out.println(&quot;Equal result is: &quot;+sum);<br>} else {<br>    System.out.println(&quot;Not Equal result is: &quot;+sum);<br>}</pre><h4>Will output “Equal result is: 0.3”</h4><h3>Why Do I need Double and Float Then?</h3><p>The main downside of using the BigDecimal class in Java is that it can be slower and use more memory than other data types such as double. This is because the BigDecimal class stores decimal numbers as a string and uses arbitrary-precision decimal arithmetic, which requires more memory and processing power to perform operations.</p><p>Another downside of the BigDecimal class is that it is less convenient to use than other data types. For example, when working with BigDecimal, you need to use its methods for performing arithmetic operations instead of using standard mathematical operators.</p><p>Additionally, the BigDecimal class is not natively supported by all platforms and hardware, which can also affect performance.</p><h3>Conclusion</h3><p>While the BigDecimal class is a suitable choice for financial and monetary calculations where a high degree of precision is required, it has some downsides such as performance and memory consumption, and it is less convenient to use than other data types. It is important to consider the specific requirements of your application and the trade-offs between precision and performance before choosing to use the BigDecimal class.</p><p><strong>Some Notes About BigDecimal:</strong></p><ul><li>BigDecimal is an immutable data type. So every method of this class should be thread safe.</li><li>A BigDecimal consists of a random precision integer unscaled value and a <strong>32-bit integer scale</strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76140af086bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bye, Bye PermGen, Hello Metaspace]]></title>
            <link>https://muratakkan.medium.com/bye-bye-permgen-hello-metaspace-4e45312adfb5?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e45312adfb5</guid>
            <category><![CDATA[metaspace]]></category>
            <category><![CDATA[permgen]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-memory-management]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 18:15:02 GMT</pubDate>
            <atom:updated>2023-01-09T18:15:02.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*E8yG7769Bf8uCe-Fgu6VCQ.jpeg" /></figure><p>In Java, the Metaspace and PermGen spaces are used to store class metadata and other class-related data.</p><p>PermGen (short for &quot;Permanent Generation&quot;) is a <strong>space in the Java Heap</strong> that was used to store class metadata in Java versions up to Java 8. PermGen was a fixed-size space, meaning that the amount of space allocated to it was predetermined at the time the Java Virtual Machine (JVM) was started. If the PermGen space filled up, it would trigger a java.lang.OutOfMemoryError, and the JVM would crash.</p><blockquote>The default maximum memory size for 32-bit JVM is 64 MB and 82 MB for the 64-bit version.</blockquote><p>However, we can change the default size with the JVM options:</p><ul><li><em>-XX:PermSize=[size]</em> is the initial or minimum size of the PermGen space</li><li><em>-XX:MaxPermSize=[size]</em> is the maximum size</li></ul><blockquote><strong>With its limited memory size, PermGen is involved in generating the famous <em>OutOfMemoryError</em></strong>. Simply put, the <a href="https://www.baeldung.com/java-classloaders">class loaders</a> weren’t garbage collected properly and, as a result, generated a memory leak.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vHVX5X9durHuTghS4H9i5A.png" /><figcaption>Heap Space up to Java 7</figcaption></figure><p>In Java 8, PermGen was replaced with Metaspace, which is a native memory space that<strong> is not part of the Java heap (Non-Heap Memory Area)</strong>. Metaspace is not fixed in size and can dynamically expand as needed. When the Metaspace space becomes full, the JVM will attempt to allocate more native memory to it. If the operating system is unable to provide the requested amount of memory, the JVM will throw an OutOfMemoryError.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*MyWVQzzdZgCxR4fWU-FUUA.jpeg" /><figcaption>Metaspace Drawing after Java 8</figcaption></figure><p>One key difference between PermGen and Metaspace is that PermGen space was garbage collected, while Metaspace is not. This means that in PermGen, objects that were no longer being used would eventually be cleaned up and the space they occupied would be made available for new objects. In Metaspace, however, unused class metadata will remain in memory until the JVM is shut down.</p><p>In summary, Metaspace and PermGen are both used to store class metadata in the JVM, but PermGen was a fixed-size space in the Java heap while Metaspace is a native memory space that can dynamically expand as needed. PermGen was also garbage collected, while Metaspace is not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e45312adfb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Memory Management 101: Java Garbage Collection]]></title>
            <link>https://muratakkan.medium.com/java-memory-management-101-java-garbage-collection-567a0720348a?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/567a0720348a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[java-memory-management]]></category>
            <category><![CDATA[garbage-collector]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 14:45:41 GMT</pubDate>
            <atom:updated>2023-01-04T11:13:56.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*Edj0hSv8fHV_kQr3OikDkg.jpeg" /></figure><p>If you’re a Java programmer, you may be familiar with the Java Virtual Machine (JVM) and the role it plays in running Java programs. One important aspect of the JVM is the garbage collection mechanism, which is responsible for freeing up memory that is no longer being used by a Java program.</p><p>In Java, memory is managed automatically using a combination of heap and stack memory. <a href="https://muratakkan.medium.com/java-memory-management-101-heap-memory-ca4060b10685">Heap memory</a> is where objects are stored, while <a href="https://muratakkan.medium.com/java-memory-management-101-stack-memory-1ea2b3bdea6f">Stack memory</a> is used to store primitive data types and references to objects.</p><p>As a Java program runs, it creates and uses objects, which consume heap memory. When an object is no longer being used, it becomes eligible for garbage collection. <strong>The garbage collector is responsible for identifying these unused objects and reclaiming the heap memory they occupy.</strong></p><p>In this blog we will try to cover Garbage Collection with these sections: Generations with GC, GC Steps, GC Process and Garbage Collectors.</p><h3><strong>Garbage Collection</strong></h3><p>Garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ixuMk8yHQXgj7ZqPTM792g.png" /><figcaption>Heap Space Representation with GC</figcaption></figure><p>To understand this section, you may need knowledge about heap space. You can read this article to learn about heap memory.</p><ul><li><a href="https://muratakkan.medium.com/java-memory-management-101-heap-memory-ca4060b10685">Java Memory Management 101: Heap Memory</a></li></ul><p>The Young Generation is where all newly created objects are allocated and aged (aging is covered in GC process section). When the young generation fills up, <strong>Minor Garbage Collection</strong> is performed and clear all unreferenced objects in young generation space.</p><p>Objects that are still being referenced by active threads and have survived the garbage collection cycle are promoted from the young generation to the old generation. When the old generation fills up, <strong>Major Garbage Collection</strong> process is performed.</p><h3>Both <strong>Major Garbage Collection </strong>and <strong>Minor Garbage Collection </strong>process “STOPS THE WORLD”.</h3><h3><strong>Stops the World?</strong></h3><p>When the garbage collector runs, <strong>it needs to stop all threads in the application</strong> so that it can safely determine which objects are no longer being used and can be collected. This pause is known as a “stop-the-world” event.</p><p>Minor Garbage collection is work on Young generation and Major Garbage Collection works on across the Heap and stops the world. Often a <strong>major collection is much slower because it involves all live objects</strong>.</p><p>There are a variety of techniques that can be used to reduce the impact of garbage collection on application performance, such as using parallel and concurrent garbage collectors.</p><h3>GC Steps</h3><blockquote>Garbage collection then goes through the three phases: <strong>mark, sweep, and, if required, compaction</strong>.</blockquote><p><strong>Marking</strong>: The process of garbage collection involves starting at the root node of the object graph (e.g., the main function in a program), and then traversing the object graph to identify objects that are reachable (i.e., still being used by the program) and unreachable (i.e., no longer being used by the program). The GC algorithm will then mark the unreachable objects as eligible for collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*yPV8xBaEPabe4lzllm3Erg.png" /><figcaption>Marking Memory Illustration</figcaption></figure><p><strong>Delete/sweep</strong>: After marking process, garbage collectors reclaim the memory occupied by unreachable objects which are marked as unreachable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*Me3LhNaUrt4CvKyALkR5VQ.png" /><figcaption>Delete/sweep Memory Illustration</figcaption></figure><p>After compacting process, Memory Allocator keeps list of references to free space in order to give free spaces when an allocation required.</p><p><strong>Compacting</strong>: Memory compaction is a process used by some garbage collection (GC) algorithms to defragment the memory heap and improve memory utilization. During compaction, the GC algorithm identifies objects that are no longer in use and reclaims their memory. It then moves the remaining objects closer together, making the allocation of memory more contiguous and reducing the amount of fragmentation. This can help to improve the efficiency of the program, as it may be able to access memory more quickly when it is contiguous, rather than having to search through fragmented blocks of memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*KVe91rvj5IthT-99647zng.png" /><figcaption>Compacting Memory Illustration</figcaption></figure><p>After compacting process, Memory Allocator keeps the beginning of references to free space in order to allocate memory squentially.</p><h3><strong>Garbage Collection Process</strong></h3><ol><li>The first step is to allocate any new objects to the eden space. Both survivor spaces start out empty.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*5IJpEyfcZSATLNeZDzb9_g.png" /></figure><p><strong>2.</strong> Minor garbage collection is triggered, when the Eden space fills up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*tm-HjwtrWKaqfUza9ligsg.png" /></figure><p><strong>3.</strong> During the garbage collection process, objects that are still being referenced by active threads are moved from the eden space to the first survivor space. Objects that are no longer referenced, or “unreferenced objects,” are deleted when the eden space is cleared. This helps to free up memory that is no longer being used by the program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*-hh-K725HGR6tWNIrxPffg.png" /></figure><p><strong>4.</strong> During the next minor garbage collection cycle, the same process occurs for the eden space. Unreferenced objects are deleted and referenced objects are moved to a survivor space. However, in this case, they are moved to the second survivor space (S1). In addition, objects from the last minor GC on the first survivor space (S0) have their age incremented and get moved to S1.</p><p>After the garbage collection process has moved all surviving objects from the eden space to the first survivor space (S1), both the eden space and the first survivor space (S0) are cleared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*bvw0YIvc_U7mT7GonVynNg.png" /></figure><p><strong>5.</strong> Additional Minor GC process repeats. However this time the survivor spaces swtich.</p><p>Maybe you have a confisuon about Why young generation has two survivor space?</p><p>In order to make contiguous (linear) access and avoid another reordering process with two space moving around and make them contiguous and relevant access. It prevents fragmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*ksnXZ9BZVLswc-RVQQp50A.png" /></figure><p><strong>6.</strong> After a minor garbage collection cycle, surviving objects that have reached a certain age threshold are “promoted” from the young generation to the old generation. In this example threshold is “7”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*MJg0wbEjA-O0z0thrOgDmA.png" /></figure><h3>Garbage Collectors</h3><p>One common misunderstanding about the Java Virtual Machine (JVM) is the belief that it only has a single garbage collector. In reality, the JVM offers<strong> four distinct garbage collectors</strong> to choose from, each with its own pros and cons. These garbage collectors include the Serial GC, Parallel GC, Concurrent Mark Sweep (CMS) GC, and Garbage First (G1) GC. Each of these garbage collectors has specific features and characteristics that make them more or less suitable for certain types of applications and environments.</p><p>The choice of which Garbage Collector to use isn’t automatic and lies on your shoulders and the differences in throughput and application pauses can be dramatic.</p><p><strong>Serial collector</strong> is the simplest one, and the one you probably won’t be using. This garbage collector is suitable for small and simple applications that have a single processor. It uses a single thread to perform garbage collection, which makes it relatively simple to implement.</p><p>You can use it by turning on this JVM argument:</p><pre>java -XX:+UseSerialGC -jar myapp.jar</pre><p><strong>Parallel Collector</strong> / Throughput Collector is the JVM’s default collector. This garbage collector is designed for multi-processor systems and uses multiple threads to perform garbage collection in parallel.</p><p>The downside to the parallel collector is that it will “Stops the World” when performing either a Minor or Major GC collection.</p><p>The parallel collector is best suited for apps that can tolerate application pauses and are trying to optimize for lower CPU overhead caused by the collector.</p><p><strong>Concurrent Collector</strong> is designed to perform garbage collection concurrently with the application. It uses multiple threads to mark and sweep objects that are no longer in use, which can reduce the overall pause time of the garbage collection process. <strong>CC only stops the world only during mark/re-mark steps.</strong></p><p>One concern when using a garbage collector that utilizes a mark-sweep-compact algorithm is the possibility of encountering promotion failures. These failures occur when the garbage collector is attempting to move objects from the old generation to the young generation at the same time as the program (also known as the mutator) is modifying the objects.</p><blockquote>To make sure this doesn’t happen you would either increase the size of the old generation (or the entire heap for that matter) or allocate more background threads to the collector for him to compete with the rate of object allocation.</blockquote><p>Another downside of thiss collector is that algorithm may use more CPU in order to provide the application with higher levels of continuous throughput. This is because the algorithm uses multiple threads to scan and collect objects, which can increase CPU usage.</p><p>In most cases, for long-running server applications that cannot tolerate application freezes,that’s usually a good trade off to make.</p><p>You have to specify this JVM argument to make CGC enable:</p><pre>java -XX:+USeParNewGC -jar myapp.jar</pre><p><strong>Garbage first collector (G1)</strong> is the newest garbage collector in Java and is designed to handle large heap sizes efficiently. It divides the heap into small regions and collects garbage in those regions that have the most free space, which can help to reduce pause times.</p><p>The G1 collector then uses multiple background threads to scan through these regions, looking for objects that are no longer in use. This allows the G1 collector to target and collect garbage in the regions that have the most free space, which can help to reduce pause times and improve the overall performance of the garbage collection process.</p><p>Introduced in JDK 7 update 4 was designed to better support heaps larger than 4GB.</p><blockquote>G1 collector is geared towards scanning those regions that contain the most garbage objects first, giving it its name (Garbage first).</blockquote><p>You have to specify this JVM argument to make G1 enable:</p><pre>java –XX:+UseG1GC -jar myapp.jar</pre><p><strong>Java 8 and the G1 Collector</strong></p><p>Another beautiful optimization introduced in Java 8 update 20 is <a href="https://medium.com/p/fbda71711435"><strong>String Deduplication</strong></a> in the G1 garbage collector. This optimization helps to reduce the amount of memory used by the application by identifying and eliminating duplicate strings. When string deduplication is enabled, the garbage collector will periodically scan the heap for duplicate strings and replace them with a single shared instance. This can significantly reduce the memory footprint of the application and improve overall performance.</p><p>You can use the <strong>-XX:+UseStringDeduplicationJVM</strong> argument to try this out.</p><h3><strong>Key notes to remember:</strong></h3><ul><li>Garbage collection is the process of identifying and eliminating unused objects in Heap Memory. The garbage collector scans the heap, determines which objects are no longer needed, and reclaims the memory occupied by those objects.</li><li>Garbage collection is carried out by a demon thread called Garbage Collector.</li><li>GC can not be forced to happen. System.gc() can be performed but it is not guaranteed! we should never invoke that explicitly, for a number of reasons; It’s costly, It doesn’t trigger the garbage collection immediately and JVM knows better when GC needs to be called.</li><li>Parallel Collector / Throughput Collector is the JVM’s default collector.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*hmUlU5QgnLc8ZFrKNUPH5A.gif" /></figure><h3><strong>References</strong></h3><ul><li><a href="https://docs.oracle.com/en/java/javase/11/gctuning/parallel-collector1.html#GUID-6C8D4E24-A580-4FEA-82F0-FE610057DD15">HotSpot Virtual Machine Garbage Collection Tuning Guide</a></li><li><a href="https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html">Java Garbage Collection Basics</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=567a0720348a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Memory Management 101: Heap Memory vs Stack Memory]]></title>
            <link>https://muratakkan.medium.com/java-memory-management-101-heap-memory-vs-stack-memory-35a1dd2e1f1d?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/35a1dd2e1f1d</guid>
            <category><![CDATA[heap-memory]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 19:20:27 GMT</pubDate>
            <atom:updated>2023-01-01T19:20:27.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDbzOYJs8DXOL45aEAWjQQ.png" /></figure><p>In order to run on the Java Virtual Machine (JVM), every Java application requires a certain amount of memory. This memory is taken from the available <strong>RAM </strong>(Random Access Memory)<strong> </strong>of the system where the application is running.</p><p>In my previous posts, I have mentioned about two memory space which can be accessible from the links below. Before starting this post please read my posts about <strong>Heap Memory </strong>and<strong> Stack Memory</strong> to understand them more detailed.</p><ul><li><a href="https://medium.com/@muratakkan/java-memory-management-101-stack-memory-1ea2b3bdea6f">Java Memory Management 101: Stack Memory</a></li><li><a href="https://muratakkan.medium.com/java-memory-management-101-heap-memory-ca4060b10685">Java Memory Management 101: Heap Memory</a></li></ul><p>In this post we will examine the differences between them and compare these two memory spaces.</p><p>Heap memory is dynamic memory that is allocated at runtime. It is typically used to store data that needs to be available for the lifetime of the program, such as objects and other variables that are created and destroyed dynamically. The heap is also used to allocate memory for data structures that may change size during the execution of the program, such as arrays and linked lists.</p><p>Stack memory, on the other hand, is static memory that is allocated at compile time. It is used to store local variables and function arguments. The stack is organized in a Last-In, First-Out (LIFO) fashion, with the most recently added data being the first to be removed.</p><blockquote>Basically, by default anything with a size known at compile-time is by default stored on the stack. The heap is generally for things which can grow, shrink, or otherwise have a size unknowable at compile-time.</blockquote><p>There are key differences between Stack memory and Heap memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*k8DpgOO1fpigrZIeBtDhWA.png" /></figure><h3>Heap <strong>memory is slower to access than stack memory</strong></h3><p>One key difference between heap memory and stack memory is that heap memory is <strong>(not always)</strong> slower to access than stack memory. This is because the <strong>heap is not organized in a contiguous block of memory</strong>, so it takes longer to locate a specific piece of data. Stack memory, on the other hand, is organized in a contiguous block and can be accessed much more quickly.</p><p>The other thing to make Stack faster is that <strong>Stack Memory is managed and optimized by the CPU quite closely</strong>. Hence reading from and writing to stack variables is very fast.</p><p>Unlike Stack memory, Heap memory is not as tightly managed by the CPU.</p><h3>Memory Size</h3><p>Heap memory is generally much larger than stack memory. This is because the stack is limited by the size of the program’s call stack, while the heap can be dynamically expanded as needed . However, this also means that heap memory is more prone to fragmentation, which can lead to performance issues.</p><ul><li><strong>The stack size is determined at compile time by the compiler.</strong></li><li><strong>The heap size varies during runtime.</strong></li></ul><p>If heap space is full, Java throws “<strong><em>java.lang.OutOfMemoryError”. </em></strong>If the stack memory is filled completely, JVM throws “<strong><em>Java.lang.StackOverFlowError”</em></strong> error.</p><h3><strong>Security</strong></h3><p>Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be accessed by the owner thread. This means that data stored on the stack is only accessible to the function that created it, and it is automatically deleted when the function returns.</p><p>Data stored in Heap Memory is available or visible to all threads, heap memory allocation is not as safe as stack memory allocation. This makes heap memory more prone to security vulnerabilities, as it can be more difficult to track and control access to the data stored there.</p><p>Overall, stack memory is generally considered to be more secure than heap memory, but both types of memory can be made more secure through careful design and implementation.</p><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*fVPFSsgPisrS1-veYKQXtg.png" /><figcaption>Heap Memory and Stack Memory Comparison Table</figcaption></figure><p>Stack memory is a linear data structure that stores items in a last-in, first-out (LIFO) manner and is managed automatically by the operating system. It is fast but has a fixed size. Heap memory is a more flexible data structure that allows for dynamic allocation and deallocation of memory and is managed by the program. It is slower but can store a larger amount of data. Stack memory is typically used for small amounts of data that are required temporarily while a program is running, while heap memory is used for larger amounts of data that are needed for longer periods of time.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35a1dd2e1f1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Memory Management 101: Heap Memory]]></title>
            <link>https://muratakkan.medium.com/java-memory-management-101-heap-memory-ca4060b10685?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca4060b10685</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[heap-memory]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 21:33:19 GMT</pubDate>
            <atom:updated>2023-01-01T19:32:13.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*fK4ZhGgxe-rgZ3U1dfsgcA.jpeg" /></figure><p>Heap memory in Java is the area of memory that is used by the JVM (Java Virtual Machine) to store objects created by the application. It is an area of memory that is shared among all the threads running in the JVM, and it is used to store objects that are created dynamically at runtime.</p><p>One of the main characteristics of heap memory is that it is an area of memory that is managed automatically by the JVM. When an object is no longer needed, the JVM will automatically reclaim the memory used by that object, a process known as <strong>Garbage Collection.</strong></p><blockquote>Unlike stack memory, heap memory is not automatically deallocated when it is no longer needed. To maintain the efficiency of memory usage, <strong>the garbage collector</strong> must be used to free up unused objects in the heap.</blockquote><p>The size of the heap memory is determined by the JVM when it starts, and it can be specified using command-line options. By default, the size of the heap is set to a specific value depending on the platform and the amount of physical memory available on the system.</p><ul><li>Use -Xms to specify the initial Java heap size</li><li>Use -Xmx to specify the maximum heap size</li><li>Use -Xmn to specify the Young generation size</li></ul><p>Example usage:</p><pre>java -Xms256m -Xmx2048m</pre><h3>The heap memory is divided into two main regions: Young Generation and Old Generation.</h3><p>The heap memory is divided into two main regions: the young generation and the old generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*4qSivQT8RkLB9NWNeauu9Q.png" /><figcaption>Heap Space Illustration</figcaption></figure><p>Young generation is further divided into two regions: the Eden space and the survivor space.</p><p><strong><em>Fun Fact:</em></strong><em> In the Holy books, It is believed that life was first created at Eden Garden.</em></p><p><strong>Eden space</strong> is where <strong>most new objects are initially allocated</strong>. When an object is no longer needed, it becomes eligible for garbage collection. If the object survives the garbage collection process, it is moved to the <strong>survivor space</strong>. If an object remains in the survivor space for a certain number of garbage collection cycles, it is moved to the tenured space (old space), which is part of the old generation.</p><p>When Eden space is filled with objects, a Minor Garbage Collection (GC) process is triggered. During this process, all the surviving objects in the Eden space are moved to one of the survivor spaces.</p><blockquote>A threshold is set for the young generation objects to be considered as the old generation. When the threshold is breached, objects are moved to the <strong>old generation. -XX:MaxTenuringThreshold </strong>parameter specifies for how many minor GC cycles an object will stay in the survivor spaces until it finally gets tenured into the old space.</blockquote><p>Example usage:</p><pre>-XX:MaxTenuringThreshold:10</pre><p>Old generation is where objects that have survived many garbage collection cycles are stored.</p><p>The old generation is collected by Garbage Collection less frequently than the young generation, and the garbage collection process is typically more time-consuming. This is because the old generation contains a larger number of objects that have a longer lifespan, and it can take longer to determine which objects are no longer needed and can be safely removed.</p><p>It is important to monitor heap space to ensure that it is not becoming too full and impacting the performance of the application. If the old generation is consistently full or is growing rapidly, it may indicate that the application is creating too many long-lived objects or that the garbage collection process is not effectively removing unneeded objects. If heap space is full, Java throws <strong><em>java.lang.OutOfMemoryError</em></strong><em>.</em></p><p>When Old Generation is full/near full, a <strong>Major Garbage Collection</strong> process is triggered.</p><p>There are a number of tools available for monitoring heap memory usage, such as the <strong>Java VisualVM</strong> tool or the <strong>Jmap command-line utility</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*YJd-xtXcTLl6U6Sg_JNIpg.png" /><figcaption>VisualVM Heap Usage Example</figcaption></figure><h3>Conclusion</h3><p>I tried to focus on basics of Java Heap Memory and its spaces. I hope the post was helpful you.</p><p>If you want to understand the Stack memory and differences between Heap Memory and Stack memory, you can access them from the links given below.</p><ul><li><a href="https://muratakkan.medium.com/java-memory-management-101-stack-memory-1ea2b3bdea6f">Java Memory Management 101: Stack Memory</a></li><li><a href="https://muratakkan.medium.com/java-memory-management-101-heap-memory-vs-stack-memory-35a1dd2e1f1d">Java Memory Management 101: Heap Memory vs Stack Memory</a></li></ul><p>Lots of Garbage collection terms are used in this post. Don’t panic! Memory Management 101: Garbage Collection post is on the way :)</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca4060b10685" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Memory Management 101: Stack Memory]]></title>
            <link>https://muratakkan.medium.com/java-memory-management-101-stack-memory-1ea2b3bdea6f?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ea2b3bdea6f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 13:42:09 GMT</pubDate>
            <atom:updated>2022-12-31T21:49:48.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*BKaxq0HZjiRP1DZx3vHeCA.png" /></figure><p>Applications require a certain amount of space (RAM) on a computer. Every time an object or variable is created within the application, it consumes additional RAM. Allocating enough memory to hold every declared value and execute each method would result in an unnecessarily large application.</p><p>To optimize the memory usage of an application, it is <strong>divided into smaller sections</strong> that require less memory and enable the application to <strong>run more efficiently</strong>. This helps to keep the overall memory requirements of the application lean and efficient.</p><h3>The Java Virtual Machine (JVM) divides the memory into two sections: <strong>HEAP</strong> and <strong>STACK memory.</strong></h3><p><strong>Before jumping into Stack memory let’s understand stack and how it works.</strong></p><p>Let me first give you an real world example how stack works.</p><p>Think about pile of clean plates for serving dinner. When the customer is ready to be served, the waitress would take the <strong>top plate from the stack</strong> and bring it to the customer’s table.</p><p>The dishwasher would then wash the dirty dishes and add the clean ones to the top of the pile of clean plates, ready to be used again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*55JG3zAliyfv2qjV4q80Tw.png" /><figcaption>Stack in a Real Life</figcaption></figure><p>As you can see from the example, top of the plate is always waiting to be served first.</p><p>This approach is called <strong>Last in First Out, also known as LIFO.</strong></p><h3><strong>Deep Dive Time to Stack Memory!</strong></h3><p>Stack memory is a special region of a computer’s memory that stores temporary <strong>variables and references</strong> used by each function, including the main() function. It is a “last in, first out” <strong>(LIFO) data structure</strong> that is managed and optimized by the CPU.</p><p><strong>How it works?</strong></p><blockquote>A key to understanding the stack memory is that whenever a method is called, a new block is created on the top of the stack to store. When a function exits, all of its variables and references are popped off of the stack (and hence lost forever).</blockquote><p>In Java, the stack memory is used to store local variables and reference variables. When a method is called, a new block is created on the top of the stack to store the method’s local variables and reference variables. When the method completes, the block is removed from the top of the stack.</p><p>The following code helps you to understand of how stack memory works.</p><pre><br>class Wizard{<br>    int age;<br>    String wizardName;<br> <br>    public Wizard(int age, String wizardName) {<br>        this.age= age;<br>        this.wizardName= wizardName;<br>    }<br>}<br> <br>public class WizardDetail{<br>    private static createWizard(int age, String wizardName) {<br>        return new Wizard(age, wizardName);<br>    }<br> <br>    public static void main(String[] args) {<br>        int age= 13;<br>        String name = &quot;Harry Potter&quot;;<br>        Wizard wizard= null;<br>        wizard= createWizard(age, name);<br>    }<br>}</pre><p>Let’s analyze this step-by-step:</p><p><strong>Allocation</strong></p><ol><li><strong>The main method </strong>is called and a block of memory is allocated on the stack for its local variables and method calls.</li><li>The local variables age and reference variable name are created in the stack and assigned the values 13.</li><li>The reference variable wizard is created in the stack.</li><li><strong>The </strong><strong>createWizard method</strong> is called and a block of memory is allocated on the stack for its local variables and method calls.</li><li>The local variables age and reference variable name are created in the stack and assigned the values 13.</li><li>The reference variable wizard is created in the stack.</li><li><strong>The </strong><strong>Wizard constructor</strong> is called block of memory is allocated on the stack for its local variables and method calls.</li><li>The local variables age and reference variable name are created in the stack and assigned the values 13.</li><li>The createWizard method returns a reference to the new Wizard object, which is assigned to the wizard variable in the main method.</li><li>The reference variable this is created in the stack.</li></ol><p><strong>Deallocation</strong></p><ol><li>The createWizard method&#39;s block of memory is freed up and returned to the stack.</li><li>The main method’s block of memory is freed up and returned to the stack.</li></ol><p>Don’t forget the the differences between reference variable and object itself. Reference variable only keeps reference value on it and it is stored in Stack memory. On the other hand, object itself is stored in Heap Memory (In this post, we did not mention the topic of heap memory). Wizard object is not stored on the Stack Memory. Only reference of Wizard is stored on Stack.</p><p>Let’s look at this example’s allocation in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*1WX9cCWg5_UyKctty9AWKQ.png" /><figcaption>Stack Memory Allocation Diagram</figcaption></figure><p>JVM stack is <strong>specific to each thread</strong>, meaning that each thread has its own separate stack. <strong>This allows multiple threads to execute concurrently</strong>, as each thread has its own set of method calls and local variables. This feature makes this space safe because the <strong>data can only be accessed by the owner</strong> <strong>thread</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*-vaEvJAnlufnXpDx6lYlmg.jpeg" /><figcaption><a href="http://www.herongyang.com/JVM/Stack-Overflow-What-Is-JVM-Stack.html">Stack and Frame illustration with owner Thread</a></figcaption></figure><p>The other important thing to remember is that we receive the corresponding error <strong>Java.lang.StackOverFlowError by JVM</strong>, If the stack memory is filled completely.</p><h3><strong>Summary</strong></h3><p>In conclusion, stack memory is a vital part of Java programming. It is used to store local variables and references of objects, which are essential for the proper functioning of a Java program.</p><p>Understanding how stack memory works can help you write more efficient and effective code in Java. It is important to keep in mind that stack memory is organized in a LIFO structure and is only accessible within the method in which it is declared.</p><p>Additionally, it is important to understand the difference between stack memory and heap memory. I will explain the Heap Memory and differences between Heap and Stack memory in another articles to avoid making this post too long and losing your focus.</p><p>You can read my post about <a href="https://muratakkan.medium.com/java-memory-management-101-heap-memory-ca4060b10685">Heap Memory</a> to continue memory management topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*6Wee0-jTQhM4PgoIYgqnTg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ea2b3bdea6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Mutability in Java]]></title>
            <link>https://muratakkan.medium.com/understanding-mutability-in-java-5083b05327cc?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5083b05327cc</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[immutable-objects]]></category>
            <category><![CDATA[mutable-objects]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[immutability]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 18:18:14 GMT</pubDate>
            <atom:updated>2022-12-26T19:18:53.501Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*nE5PO0naHVQtmHgCl8gETw.jpeg" /></figure><p>Are you tired of the boring, dry explanations of mutable and immutable objects? Well, fear not! In this blog, we’ll take a more lighthearted approach to understanding these concepts.</p><p>First, let’s start with the basics. In Java, an object is considered <strong>immutable</strong> if its <strong>state cannot be modified once it is created</strong>. In other words, you can’t change the innards of an immutable object no matter how hard you try. It’s like trying to change the laws of physics — it just ain’t gonna happen.</p><p>Now, you might be wondering, “<strong>Why on earth would I want to use immutable objects if they can’t be changed?</strong>” Good question! It turns out that immutable objects have a few key benefits.</p><p>Imagine you’ve got a bunch of threads running around, all trying to access the same object. If that object is mutable, it’s like trying to have a conversation with a group of people who are all talking at the same time. It’s chaotic and nobody can understand what’s going on. But if the object is immutable, it’s like having a conversation with a group of people who are all talking one at a time. Everything is much clearer and easier to follow.</p><p>Now, we know what you’re thinking: “<strong>But wait, doesn’t that mean I can never change the state of an immutable object</strong>?” Well, <strong>not exactly</strong>. You see, even though the object itself is immutable, it can still contain references to mutable objects. It’s like having a group of people who all have to raise their hand before they speak. The group itself is immutable, but the individuals within it can still change their minds and raise their hands whenever they want.</p><p>In other words, Immutable objects are <strong>thread-safe</strong>. Since their state can’t be modified, there’s<strong> no need to synchronize access</strong> to them. This makes them particularly useful in concurrent environments, where multiple threads may be accessing the same object.</p><p><strong>On the other hand, a mutable object</strong> is like a chameleon — it can change its state to fit whatever situation it finds itself in. This means that it is possible to change the object’s state in-place, without creating a new object.</p><p><strong>Mutable objects</strong> have a few key advantages in Java programming.</p><p><strong>Flexibility</strong>: Mutable objects can be modified at any time, which can be useful in situations where the state of the object needs to change frequently. This can be especially useful in situations where the state of the object depends on user input or other external factors.</p><p><strong>Ease of use</strong>: In some cases, mutable objects can be easier to work with than immutable objects. For example, it may be simpler to modify an existing mutable object rather than creating a new immutable object each time the state needs to change.</p><p><strong>Performance</strong>: In some cases, mutable objects can be more efficient than immutable objects. For example, modifying an existing mutable object may be faster than creating a new immutable object, particularly if the object is large or complex.</p><h4>Mutable and Immutable Objects in Java</h4><p>Let’s continue with an example to understand immutable object in java.</p><p>Here is an example of an immutable object in Java:</p><pre>public final class ImmutableObject {<br>    private final int value;<br><br>    public ImmutableObject(int value) {<br>        this.value = value;<br>    }<br><br>    public int getValue() {<br>        return value;<br>    }<br>}</pre><p>In this example, the ImmutableObject class has a single field, value, which is marked as final. This means that the value of the field cannot be changed after the object is created. The class also does not have any methods that allow the value to be modified, so the object&#39;s state remains unchanged.</p><p>Here is an example of how to use an immutable object in Java:</p><pre>ImmutableObject obj = new ImmutableObject(10);<br>System.out.println(obj.getValue());  // Outputs: 10<br><br>// The following line will cause a compilation error, because the value field is marked as final<br>obj.value = 20;<br><br>// To change the value of the object, we must create a new instance with the new value<br>obj = new ImmutableObject(20);<br>System.out.println(obj.getValue());  // Outputs: 20</pre><p>In java <strong>String</strong>, <strong>all legacy classes, Wrapper class</strong> (<strong>Integer, Byte, Long, Float, Double, Character, Boolean and Shor</strong>t)<strong> etc. </strong>are an immutable.</p><p>As you can see in the picture below if you assign new value to immutable primitive wrapper class ,memory will create a new object and not modify the old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*44kqJCQNtF-AloiNu4SjPw.png" /><figcaption>Immutable Objects Memory Representation by <a href="https://pythonsimplified.com/mutability-immutability-in-python/">pythonsimplified</a></figcaption></figure><p>If we understand the example of immutable object, Let’s create mutable object!</p><pre>public class MutableObject {<br>    private int value;<br><br>    public MutableObject(int value) {<br>        this.value = value;<br>    }<br><br>    public int getValue() {<br>        return value;<br>    }<br><br>    public void setValue(int value) {<br>        this.value = value;<br>    }<br>}</pre><p>In this example, the MutableObject class has a single field, value, which can be accessed and modified using the getValue and setValue methods. This means that the state of a MutableObject can be changed after it is created, as shown in the following example:</p><pre>MutableObject obj = new MutableObject(10);<br>System.out.println(obj.getValue());  // Outputs: 10<br><br>obj.setValue(20);<br>System.out.println(obj.getValue());  // Outputs: 20</pre><p>As you can see, the value of the MutableObject can be changed by calling the setValue method, which allows the object&#39;s state to be modified in-place. This is an example of a mutable object in Java.</p><p>There are several built-in mutable objects in Java that you can use in your programs like StringBuilder, HashMap, java.util.Date etc.</p><h4><strong>Conclusion</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*TDs5W7fjtAt4Csl_KHtqsw.gif" /></figure><p>So, which type of object should you use? It really depends on your needs. If you need an object that can change its state on the fly, a mutable object might be the way to go. But if you need a little more stability in your life an immutable object might be the better choice.</p><p>Just remember: <strong>with great power comes great responsibility</strong>. Use mutable and immutable objects wisely, or you might end up with a codebase that’s as chaotic as a chameleon trying to blend in with a rainbow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5083b05327cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Using the Java String Pool in Java]]></title>
            <link>https://muratakkan.medium.com/understanding-and-using-the-java-string-pool-in-java-d60d3176716?source=rss-655192aecf6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d60d3176716</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[string-pool]]></category>
            <category><![CDATA[java-performance]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Murat]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 13:31:48 GMT</pubDate>
            <atom:updated>2022-12-31T22:05:23.808Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Java String Pool</em> is a special storage area in the <a href="https://muratakkan.medium.com/java-memory-management-101-heap-memory-ca4060b10685"><strong>Java heap</strong></a> where string literals are stored. It is implemented to improve the performance of string operations and to conserve memory. It is also known as <strong>String Intern Pool</strong> or <strong>String Constant Pool.</strong></p><p>When you create a new string literal from the String class, the JVM will first check if the string already exists in the string pool. If it does, the JVM will return a reference to the existing string object, rather than creating a new object. This is known as string interning.</p><p>For example, consider the following code:</p><pre>String s1 = &quot;Harry Potter&quot;;<br>String s2 = &quot;The Lord of the Rings&quot;;<br>String s3 = &quot;Harry Potter&quot;;</pre><p>In this code, the JVM will create a single string object with the value “Harry Potter” and store it in the string pool. Both s1 and s3 will be references to this single string object.</p><p>If the literal is not present in the pool (“The Lord of the Rings) , a new String object takes place in the String pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*3r0gH8Hl_B0e6EZqX6fM8w.png" /><figcaption>String Pool representation with String literal</figcaption></figure><p><strong>Using the String Pool</strong></p><p>There are two ways the create String in Java programming language. The first way is using <strong>String Literal</strong> and the other way is using <strong>new keyword</strong>.</p><p>String literal object creation example:</p><pre>String s1 = &quot;Harry Potter&quot;;<br>String s2 = &quot;The Lord of the Rings&quot;;<br>String s3 = &quot;Harry Potter&quot;;</pre><p>String creation example with new keyword:</p><pre>String s4 = new String(&quot;Harry Potter&quot;);<br>String s5 = new String(&quot;The Lord of the Rings&quot;);</pre><p>Let’s understand what is the difference between them. Let’s compare the string literals’ references.</p><pre>s1==s3 //true<br>s1==s4 //false</pre><p>Short Reminder! When you compare two objects using == operator, It compares addresses in the memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*CXq-tsMtfyqYBo9KHiWqug.png" /><figcaption>String Pool representation with String literal and New Keyword</figcaption></figure><p>As you can see the picture and example in the above, whenever we use a <strong>new</strong> operator to create a string it creates a new string object in the <a href="https://muratakkan.medium.com/java-memory-management-101-heap-memory-ca4060b10685">Java heap</a> and don’t check the object whether its in the String pool or not.</p><h4>String.intern() Method</h4><p>String literals are automatically interned, which means that they are stored in the string pool. However, you can also intern strings manually using the intern() method of the String class. This is useful if you want to ensure that a particular string is stored in the string pool and can be shared by multiple variables or objects.</p><pre>String s6 = new String(&quot;The Lord of the Rings&quot;).intern();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*TD1YQQjoGnxJLEQ_w2ouzA.png" /><figcaption>Intern Method Usage</figcaption></figure><p>Now we can see that;</p><pre>s2==s6 //true<br>s2==s5 //false</pre><p><strong>Benefits of the String Pool</strong></p><ul><li>Improved performance: Because the JVM can return a reference to an existing string object rather than creating a new one, string operations are faster when using the string pool.</li><li>Memory conservation: The string pool helps to conserve memory by avoiding the creation of unnecessary string objects.</li><li>Shared strings: The string pool allows you to share strings between different variables and objects, which can be useful for reducing the memory footprint of your program.</li></ul><p><strong>Downside of String Pool</strong></p><p>it can lead to decreased performance. Retrieving a string from the pool requires a search through all of the strings in the pool, which can be slower than simply creating a new string object. This is especially true if the program creates and discards a large number of strings, as the string pool will need to be searched each time a string is used.</p><p><strong><em>Some Notes to Remember</em></strong></p><ul><li>String pool is an example of the Flyweight Design Pattern.</li><li>All literal strings and string-valued constant expressions are interned.</li></ul><blockquote>Before Java 7, the JVM <strong>placed the Java String Pool in the <em>PermGen</em> space, which has a fixed size — it can’t be expanded at runtime and is not eligible for garbage collection</strong>.</blockquote><blockquote>The risk of interning <em>Strings</em> in the <em>PermGen </em>(instead of the <em>Heap</em>) is that <strong>we can get an <em>OutOfMemory</em> error</strong> from the JVM if we intern too many <em>Strings</em>.</blockquote><blockquote>From Java 7 onwards, the Java String Pool is <strong>stored in the </strong><a href="https://muratakkan.medium.com/java-memory-management-101-heap-memory-ca4060b10685"><strong><em>Heap</em> space</strong></a><strong>, which is garbage collected</strong> by the JVM<em>. </em>The advantage of this approach is the <strong>reduced risk of <em>OutOfMemory</em> error</strong> because unreferenced <em>Strings</em> will be removed from the pool, thereby releasing memory.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d60d3176716" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>