<?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 Rakshapriyan on Medium]]></title>
        <description><![CDATA[Stories by Rakshapriyan on Medium]]></description>
        <link>https://medium.com/@rakshapriyanraksha?source=rss-f37c0eede6d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aLqDagzawTBWMeLQ</url>
            <title>Stories by Rakshapriyan on Medium</title>
            <link>https://medium.com/@rakshapriyanraksha?source=rss-f37c0eede6d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:25:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rakshapriyanraksha/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[From Campus to Corporate: My Zoho Internship Journey]]></title>
            <link>https://medium.com/@rakshapriyanraksha/from-campus-to-corporate-my-zoho-internship-journey-7983421e3b9d?source=rss-f37c0eede6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7983421e3b9d</guid>
            <category><![CDATA[zoho]]></category>
            <category><![CDATA[internship-at-zoho]]></category>
            <category><![CDATA[rakshapriyan]]></category>
            <category><![CDATA[internships]]></category>
            <dc:creator><![CDATA[Rakshapriyan]]></dc:creator>
            <pubDate>Sat, 03 May 2025 20:57:16 GMT</pubDate>
            <atom:updated>2025-05-04T04:27:06.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehVE4oT9P2bkANGtk3cFow.jpeg" /></figure><h3>The Night Before Everything Changed</h3><p>It’s funny how life can switch from laid-back to life-changing in a matter of hours. The day before my first aptitude assessment for Zoho’s internship drive at my college, I was in Bangalore, casually hanging out with friends. It wasn’t until late that night — just hours before the test — that I began brushing up on previous years’ Zoho aptitude questions. It wasn’t ideal, but it was honest.</p><h3>Selection Day:</h3><p>The next morning, my college campus buzzed with energy — nearly 1,800 students had gathered for the assessment. The test had two parts: aptitude MCQs and technical MCQs. While aptitude has never been my strong suit, I managed to get almost all the questions right — probably missed just two. For the technical section, I felt more confident and got nearly everything correct except one or two questions.</p><p>After the test, we were asked to wait for the results, as there might be a coding round in the afternoon. Soon, the list was out — and to my delight, my name was on it.</p><h3>The Coding Challenge That Changed Everything</h3><p>That afternoon, we were given five programming questions on paper, spread across five sheets. I went through each one and was able to solve them all. It gave me a quiet confidence — I knew I had made it to the next round.</p><p>The next day brought Round 3 — the long-format coding round. The night before, I tried to mentally prepare by watching YouTube videos about previous Zoho interviews, hoping to get a sense of what might come. Sure enough, the task was substantial: I was asked to develop a console-based Attendance Management System. It wasn’t just about writing code — it was about building something functional, efficient, and clean from scratch.</p><p>I gave it my all. I structured the application, implemented basic CRUD operations, handled edge cases, and focused on clean output formatting. Once I submitted my solution, I felt a deep sense of satisfaction.</p><h3>Cracking the Interview</h3><p>Then came the interview rounds — one after another. I was interviewed by 4 to 5 people, each with their own set of questions, ranging from programming logic and problem-solving to object-oriented design and system thinking. I answered most questions confidently, drawing from both what I’d learned in college and what I had picked up through personal projects and practice.</p><p>Finally, at around 8 PM, fifteen of us were called into the placement cell. The tension was real. When the results were announced, 12 of us received full-time offers. It was one of the most memorable moments of my academic life — an intense, rewarding journey from uncertainty to achievement.</p><h3>First Days: When Disappointment Turns to Discovery</h3><p>Like every fresher stepping into the corporate world for the first time, I was a mix of excitement, nervousness, and curiosity on my first day at Zoho. The onboarding process was held online, where we were walked through company policies, team expectations, and general instructions. But what followed was something none of us expected.</p><p>Out of the 12 of us who were selected, 5 were assigned to a small regional office — and when we first saw it, we couldn’t help but feel a wave of disappointment. It wasn’t the big, bustling tech campus we had envisioned. But things quickly changed.</p><p>After the onboarding, we began interacting with the people at that office — and to our surprise, they were incredibly friendly and welcoming. Conversations started flowing, and so did laughter. They even taught us how to play table tennis, and soon, what felt like a letdown turned into a space of camaraderie and comfort.</p><p>Since our actual training was postponed to wait for students joining from other colleges, we were given a simple instruction: “Get a strong grip on Java.” They handed us the classic Head First Java book and told us to dive deep into the language — not just the syntax, but the concepts, the design, the “why” behind the code.</p><p>So that’s what we did — reading Head First Java, discussing concepts with each other, and slowly building our foundation. It was a chance to prepare, bond, and transition from student life to the professional world.</p><h3>The Real Training Begins: Java Deep Dive</h3><p>Nearly two months into the internship, the real training finally began — and this was where, to put it bluntly, the real grind started. We were shifted to the Karaikudi office, another small regional setup. But by then, we were used to compact workspaces and found comfort in the familiarity and routine.</p><p>The training was structured yet intense. We were assigned tasks in core Java concepts, one by one, each followed by practical tasks that tested not just our understanding, but our ability to write clean, optimized, and production-level code. This was the phase where I truly began to understand what Java really is — beyond the syntax — the design, the architecture, the performance.</p><h3>Daily Competition: Reviews That Pushed Me Further</h3><p>After completing a topic and submitting our task, we would face one-on-one reviews with our lead. But here’s the twist — he wouldn’t just check our work. He’d ask questions from every possible angle related to the topic. In a way, he became our daily competition. This pushed me to prepare deeply before submitting anything — I didn’t just want my code to run, I wanted to defend it confidently.</p><p>But just when I was gaining momentum, reality struck — college exams. Our training was frequently interrupted by having to return to college, and that completely broke the rhythm. The exams stretched for over a month, and it took 2–3 days every time just to get back into the flow.</p><h3>First Real Project: Building a NetBanking System From Scratch</h3><p>Despite the breaks, we kept pushing. After completing the series of topic-wise tasks, we were given our first real-world mini project: to build a NetBanking system from scratch. It was our first taste of building a complete application — planning the modules, designing the flow, and writing actual backend logic as if we were working in a live environment.</p><p>As part of our training, we were tasked with developing a NetBanking application from scratch, using the following tech stack:</p><ul><li><strong>Backend</strong>: Java 8, J2EE</li><li><strong>Database</strong>: MySQL 5</li><li><strong>Frontend</strong>: HTML, CSS, JavaScript</li></ul><p>This wasn’t just a sample project — it was treated like a real-world application. We had to plan everything from the ground up, starting with designing a complete ER diagram. Once that was approved by our lead, the real challenge kicked in.</p><h3>The Dynamic Data Access Layer: My Biggest Technical Challenge</h3><p>Our first major task was to build the underlying data access layer — a reusable, generic layer responsible for performing CRUD operations on any table in the database. This wasn’t just plain JDBC. We had to build it in such a way that:</p><ul><li>It could dynamically construct queries.</li><li>It would work independently of table structure.</li><li>It would map POJO classes to DB tables using a YAML file.</li></ul><p>This YAML-based mapping helped in abstracting table names, column mappings, and relationships, making our code cleaner and more scalable. But it also introduced a new level of complexity.</p><h3>Parent-Child Relationships: The Database Dance</h3><p>To make it even more interesting — and by that, I mean more painful — the database schema included parent-child relationships between tables. That meant:</p><ul><li>When a parent entity was added, its child records had to be created automatically.</li><li>Any update or delete operation on a parent had to cascade to the children — with full consistency.</li></ul><p>This layer took us over 5 days of intense debugging, and optimizing. But it was also where I learned the most — not just about Java or databases, but about writing scalable and maintainable enterprise code.</p><h3>Struggling with CSS in Frontend</h3><p>Once we had completed the most complex part — the dynamic backend layer and database integration — the rest of the backend logic came together relatively quickly. We moved module by module, steadily building the core functionalities of the NetBanking system.</p><p>Then came the part I was least confident about: the frontend.</p><p>While I was fairly comfortable with HTML and could manage JavaScript, CSS was my kryptonite. I’d never really spent enough time with it before, and now I was expected to build a responsive, functional, and clean UI that matched specific design expectations.</p><p>What made it even harder was the feedback loop. After submitting a page, our lead would suggest changes — sometimes minor, sometimes massive. For me, even the smallest UI adjustments took hours of CSS trial-and-error. Meanwhile, others around me were cruising through their frontends. It was frustrating, but also humbling.</p><p>What should have taken about a week ended up stretching to 15–20 days. I spent those weeks learning by failing — breaking things, rebuilding them, scouring forums, watching CSS tutorials at night, and slowly, painfully improving.</p><p>Eventually, I managed to complete the frontend, fully integrate it with the backend, and ensure everything worked seamlessly. It wasn’t perfect — but it was mine, and it worked.</p><h3>Securing the Castle: Building Robust Backend Security</h3><p>I began focusing heavily on making the backend robust and secure, which included:</p><ul><li>Implementing Authentication &amp; Authorization to control user access levels (Customer, Manager &amp; Employee).</li><li>OTP verification through email for sensitive transactions like fund transfers or account edits.</li><li>Password hashing using industry-standard algorithms to store credentials safely.</li><li>Data encryption for sensitive user information in transit and at rest.</li><li>Input validation and sanitization to prevent SQL injections and other common attack vectors.</li><li>Preparing for session management, including login expiration and refresh flows.</li></ul><p>These weren’t just features — they were habits forming in me as a developer: thinking from the user’s safety perspective and understanding why clean code and solid architecture matter.</p><h3>Writing Code That Lasts Long</h3><p>I realized quickly that without a solid structure, even a small change could break the entire system. So I restructured the codebase into a more professional, layered architecture:</p><ul><li>Presentation Layer (UI, form data)</li><li>Controller Layer (Handles API calls &amp; user requests)</li><li>Service Layer (Business logic)</li><li>Repository/DAO Layer (Database interaction)</li><li>Config &amp; Util Layer (Reusable utilities, configuration)</li></ul><p>This separation of concerns helped in:</p><ul><li>Debugging faster</li><li>Adding new features without breaking existing ones</li><li>Collaborating with teammates more efficiently</li><li>Testing individual units of code in isolation</li></ul><p>It wasn’t easy — I had to go back and refactor a lot of code, and at times it felt like starting over. But that pain taught me the value of writing code for the future, not just the present.</p><h3>Team Synergy: Learning the Power of Peer Reviews</h3><p>This phase also taught me how real software is built in collaboration:</p><ul><li>We held peer reviews where teammates would point out inefficiencies or design flaws.</li><li>I learned to accept feedback without ego, and explain my design choices clearly.</li><li>We started following naming conventions, comment standards, and version control best practices.</li></ul><p>Sometimes, a teammate’s one-liner tip saved me hours of debugging. Other times, I was able to help someone structure their logic better. That sense of growth — both as a developer and a team player — was new and fulfilling.</p><h3>From Theory to Practice: SOLID Principles in Action</h3><p>After securing the core structure of the application — its security, architecture, and essential functionality — I began diving deeper into Design Patterns and the SOLID principles. These weren’t just theoretical concepts anymore. By applying them, I was able to make the code cleaner, more modular, and easier to maintain.</p><p>For instance:</p><ul><li>I applied Dependency Injection to decouple tightly bound components.</li><li>I used the Single Responsibility and Open/Closed Principles to simplify and improve the readability of the code.</li><li>Design patterns like Factory, Strategy, and Singleton played a crucial role in organizing the project and making it more extensible.</li></ul><p>What I realized was that applying design principles didn’t just improve the code, it made me a better developer. It taught me the importance of thinking in terms of maintainable solutions and not just functional ones.</p><h3>Testing the Tough Scenarios</h3><p>As the application became more feature-rich, I transitioned to manual testing, actively seeking edge cases to ensure the application’s robustness. I tried everything: entering invalid inputs, and attempting other scenarios that could break the system.</p><p>This process was essential because every bug or flaw I found led to new features, validation checks, and workflow improvements. It taught me an important lesson:</p><blockquote><em>“A project can be completed in a week, or it can be improved for years — the choice is yours.”</em></blockquote><p>It was a mindset shift. While it was tempting to call the project “done,” I realized that real craftsmanship lies in continually improving and refining until the product becomes something you can truly be proud of.</p><h3>Learning by Teaching</h3><p>One of the most effective parts of my training was the teaching sessions. Every week, each of us was assigned a complex topic — be it Java concepts, design patterns, or advanced concepts. We would thoroughly prepare and then present our findings to the group.</p><p>This approach didn’t just deepen my understanding of the topics, it also enhanced my ability to communicate complex ideas clearly and confidently. Through this experience, I realized how much teaching can enhance learning. It made me more self-assured and gave me the ability to approach any technical challenge with clarity.</p><h3>The Final Review: Moment of Truth</h3><p>The final phase of our training took us to Zoho’s head office in Chennai for our final review. Before the review, we had a code walkthrough with a lead, where we received tough but constructive feedback. We worked hard to incorporate the suggestions, making the necessary changes to improve our work.</p><p>Finally, the review day arrived. We presented our work, walked through the architecture, and explained the decisions we had made. And when it was all over, the moment I had been working toward arrived — I was offered a full-time role at Zoho.</p><p>It was the result of months of hard work, growth, and countless lessons learned — and it felt incredibly rewarding.</p><h3>The Crossroads: A Difficult Decision</h3><p>While I was offered a full-time role at Zoho, I had already started exploring other opportunities during my project development phase. I wasn’t entirely sure about my chances of converting to a full-time role at Zoho, so I began looking for other avenues. Fortunately, or perhaps unluckily, I received an internship offer from another organization before I secured the full-time position at Zoho.</p><p>This created a massive dilemma for me: Which company should I choose?</p><p>I had a few critical factors to weigh in my decision:</p><ol><li><strong>The Stack at Zoho</strong>: While Zoho provided an excellent working environment and a strong support system, the tech stack they used was relatively outdated. They primarily focused on maintaining legacy systems, and the opportunity to build something entirely new was limited.</li><li><strong>The New Opportunity</strong>: On the other hand, the organization that offered me the internship was using cutting-edge technologies, and I saw an incredible opportunity there to build new products from scratch. This aligned more with my long-term goals of product development rather than just maintenance.</li><li><strong>The Work Environment</strong>: Zoho’s work culture and environment were exceptional. The support, the people, the encouragement — everything about the company was fantastic. But, I found myself at a point where I wanted to push the boundaries, learn newer stacks, and be part of something innovative and groundbreaking.</li></ol><h3>The Road Not Taken: Making the Hard Choice</h3><p>After much deliberation, and seeking advice from mentors and peers, I made the tough choice to accept the new opportunity. Leaving Zoho wasn’t easy, especially after all the growth and learning I had experienced. However, I knew that at this point in my career, developing new products and learning modern technologies were paramount for me.</p><p>I will always be grateful to Zoho for everything it taught me — from technical skills to work culture. The training, the projects, the challenges, and most importantly, the wonderful people I met there, will always hold a special place in my heart.</p><h3>Looking Back: What Zoho Gave Me</h3><p>Zoho was where I began my professional journey, and I’ll always remember it as the place that shaped me into the developer I am today. I may not be continuing with Zoho, but the lessons learned there will continue to guide me in my future endeavors.</p><p>In the end, my internship at Zoho wasn’t just about learning to code better — it was about understanding what kind of developer I wanted to be, what kind of problems I wanted to solve, and what kind of career I wanted to build. And for that clarity alone, I’ll always be thankful for my time there.</p><p><em>This article reflects my personal journey and experiences at Zoho. Every internship experience is unique, and I hope sharing mine provides some insight to others beginning their careers in tech.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7983421e3b9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Memory Model and Hardware Architecture: Bridging the Gap for Concurrency]]></title>
            <link>https://medium.com/@rakshapriyanraksha/java-memory-model-and-hardware-architecture-bridging-the-gap-for-concurrency-5e661e098d53?source=rss-f37c0eede6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e661e098d53</guid>
            <category><![CDATA[jvm-architecture]]></category>
            <category><![CDATA[java-memory-model]]></category>
            <category><![CDATA[synchronization-in-java]]></category>
            <category><![CDATA[concurrency-in-java]]></category>
            <dc:creator><![CDATA[Rakshapriyan]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 08:45:03 GMT</pubDate>
            <atom:updated>2025-02-14T08:45:03.095Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Ever written a perfectly fine multi-threaded Java program, only to see it behave unpredictably on different machines? One moment, everything works smoothly, and the next, race conditions and visibility issues creep in. The culprit? The intricate dance between the </em><strong><em>Java Memory Model (JMM)</em></strong><em> and the </em><strong><em>underlying hardware architecture</em></strong><em>. CPUs optimize execution by reordering instructions, caches store values inconsistently across cores, and memory barriers enforce rules we rarely notice — until things go wrong.</em></p><p>In this deep dive, we’ll explore how the JMM and hardware interact, why this matters for writing concurrent programs, and how you can bridge the gap to write thread-safe, high-performance Java applications.</p><h3>Why Should You Care About JMM and Hardware Architecture?</h3><p>Imagine debugging a multi-threaded Java application. Your code looks correct — no obvious race conditions, proper synchronization — but threads still behave unpredictably. Sometimes they see updates instantly; sometimes, they don’t.</p><p>This isn’t just a Java problem — it’s a hardware problem. CPUs are designed for efficiency: they <strong>reorder instructions</strong>, <strong>cache values in unpredictable ways</strong>, and <strong>follow their own memory consistency rules</strong>. Even if your Java code adheres to the JMM, the hardware may not behave as expected. Understanding this interaction is key to writing reliable concurrent programs.</p><h3>Understanding Java Memory Model:</h3><p>The <strong>Java Memory Model (JMM)</strong> defines how threads interact with memory, ensuring consistent execution across different systems. It governs <strong>synchronization, visibility, and ordering</strong> of memory operations in multi-threaded programs.</p><h4>The Stack and the Heap: A Closer Look</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtC1Qy7yC4O-bq7WVk-AHg.jpeg" /></figure><p>When a Java program runs, it needs a place to store data and keep track of what’s happening. The <strong>Java Virtual Machine (JVM)</strong> divides memory into different sections to ensure everything runs smoothly. The two most important areas are the <strong>stack</strong> and the <strong>heap</strong>, each with a specific purpose.</p><h4>Stack Memory: Thread-Specific and Fast</h4><p>Every thread in Java has its own stack, which is like a notepad where it writes down the steps it’s following. When a method is called, the JVM adds it to the top of the stack. Once the method finishes, it gets erased. Along with method calls, the stack also stores <strong>local variables</strong> — temporary data used only while a method is running.</p><p>The important thing about stack memory is that each thread gets its own separate stack. This means local variables from one thread are completely invisible to other threads. If two threads run the same method, they will each have their own private copies of the method’s variables.</p><h4>Heap Memory: Shared and Dynamic</h4><p>The <strong>heap</strong> is where Java stores objects. Unlike the stack, which is thread-specific, the heap is shared among all threads. Every time you create an object using new, it goes into the heap. Even if an object is created inside a method, it still lives in the heap, while the reference to that object is stored in the thread’s stack.</p><p>If multiple threads have a reference to the same object, they can all access and modify it. This is where things get tricky — if two threads modify the same object, it can lead to unexpected behavior. That’s why Java provides synchronization mechanisms to help manage access to shared data.</p><h3>Memory Visibility Problem:</h3><p>The biggest challenge in concurrency isn’t just race conditions but <strong>memory visibility</strong> — when one thread updates a shared variable, another thread might not see the change immediately.</p><p>Why? Because modern CPUs use multi-level <strong>caching (L1, L2, L3)</strong> to improve performance. When <strong>Thread A</strong> updates a variable, the new value might stay in its local cache rather than being written to <strong>main memory</strong>. Meanwhile, <strong>Thread B</strong>, running on another core with its own cache, might still see the old value. This leads to <strong>stale reads</strong> and unpredictable behavior.</p><h3>How JMM helps?</h3><p>The JMM is designed to address these visibility issues by defining a set of rules that govern how and when changes made by one thread become visible to others. The JMM introduces concepts like <strong>happens-before relationships</strong>, <strong>memory barriers</strong>, and <strong>synchronization</strong> to ensure predictable behavior in multi-threaded programs.</p><h4>Happens-Before Relationship &amp; Synchroniztion:</h4><p>The <strong>happens-before relationship</strong> guarantees that if one action <em>happens-before</em> another, the results of the first action are visible to the second. This is essential to ensure that threads see the most up-to-date values of shared variables.</p><p>For example, consider two threads working with a shared variable x:</p><ul><li><strong>Without a happens-before relationship</strong>, Thread B may read a stale value of x, leading to unpredictable behavior.</li></ul><h4>Examples of Happens-Before Relationships:</h4><p><strong>1. volatile Variables</strong></p><p>A write to a volatile variable happens-before any subsequent read of that variable by another thread. It writes directly to the main memory.</p><pre>volatile int x = 0;<br>// Thread A<br>x = 10; // Write to x<br>// Thread B<br>System.out.println(x); // Guaranteed to see x = 10</pre><p><strong>2. synchronized Blocks</strong></p><p>When a thread exits a synchronized block, all actions inside that block <strong>happen-before </strong>any other thread enters a synchronized block locking on the same object.</p><pre>Object lock = new Object();<br>int y = 0;<br><br>// Thread A<br>synchronized (lock) {<br>    y = 20; // Write to y<br>}<br><br>// Thread B<br>synchronized (lock) {<br>    System.out.println(y); // Guaranteed to see y = 20<br>}</pre><h4><strong>3. </strong>Thread Start and Join</h4><ul><li>Thread.start() happens-before any action in the newly started thread.</li><li>Thread.join() happens-before the main thread continues execution.</li></ul><pre>Thread t = new Thread(() -&gt; x = 10);<br>t.start();<br>t.join(); // Ensures main thread sees x = 10</pre><h3>Hardware Memory Architecture:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgkoZkRlrWjxLKhepiOiDA.jpeg" /><figcaption>Hardware Memory</figcaption></figure><p>Modern computers typically contain multiple <strong>Central Processing Units (CPUs)</strong>, also known as cores. Each core can execute instructions independently, meaning multiple threads can run in parallel on different cores.</p><p>In addition to the CPUs themselves, a computer system consists of various layers of memory:</p><ul><li><strong>Registers</strong> (fastest, smallest, inside the CPU)</li><li><strong>CPU Cache Memory</strong> (fast, small, closer to the CPU)</li><li>L1 Cache (closest to the CPU, fastest)</li><li>L2 Cache (slightly larger, slower than L1)</li><li>L3 Cache (shared among multiple cores, slower than L2)</li><li><strong>Main Memory (RAM)</strong> (larger but much slower than cache)</li></ul><h4>Cache Hierarchy in Modern CPUs</h4><p>Most CPUs have a multi-level cache system:</p><ol><li><strong>L1 Cache (Level 1)</strong> — Closest to the CPU, smallest (typically 32–256 KB per core), and fastest. Each core has its own L1 cache.</li><li><strong>L2 Cache (Level 2)</strong> — Larger (typically 256 KB — 1 MB per core) but slightly slower than L1. Each core may have a private L2 cache.</li><li><strong>L3 Cache (Level 3)</strong> — Shared across multiple cores in a CPU. It is much larger (typically 2 MB — 64 MB), but slower than L2.</li></ol><h4>Cache Lines and Cache Coherence</h4><p>Cache memory is divided into <strong>cache lines</strong> (typically 64 bytes). When a CPU loads a variable from main memory, it brings an entire cache line containing the variable into the CPU cache. If another CPU modifies the same memory location, cache coherence protocols ensure all copies of the data remain consistent.</p><h3>Bridging the Gap for Concurrency:</h3><p>When writing multithreaded programs in Java, understanding how <strong>Java’s Memory Model (JMM)</strong> interacts with <strong>hardware memory architecture</strong> is crucial. In modern computers, memory is structured in layers — from <strong>CPU registers</strong> to <strong>caches</strong> to <strong>main memory (RAM)</strong>. This setup can create <strong>visibility issues</strong> and <strong>race conditions</strong> when multiple threads access shared data.</p><p>Let’s break these concepts down into <strong>simple terms</strong> and look at how we can solve these problems in Java.</p><h4>How Threads Access Memory in Java</h4><p>When a thread accesses a variable, it does not always read it directly from <strong>main memory (RAM)</strong>. Instead, it might use <strong>CPU caches</strong> for faster access.</p><ul><li><strong>Each CPU has its own cache</strong>, meaning different threads might see <strong>different copies</strong> of the same variable.</li><li>If changes made by one thread <strong>do not get updated in main memory</strong>, other threads will still see an <strong>old value</strong>.</li><li>This leads to <strong>inconsistencies</strong>, known as <strong>visibility issues</strong> and <strong>race conditions</strong>.</li></ul><h3>Problem 1: Visibility Issues</h3><h4>What Happens Without volatile?</h4><p>Imagine we have a <strong>shared variable</strong> that one thread updates while another thread reads it.</p><h4>Example Without volatile (Visibility Issue)</h4><pre>class SharedResource {<br>    int count = 0;  // Shared variable<br>}<br>class WorkerThread extends Thread {<br>    SharedResource resource;<br>    WorkerThread(SharedResource resource) {<br>        this.resource = resource;<br>    }<br>    public void run() {<br>        System.out.println(&quot;Updating count...&quot;);<br>        resource.count = 5;  // This update might not be visible to other threads immediately!<br>    }<br>}<br>public class VisibilityProblem {<br>    public static void main(String[] args) throws InterruptedException {<br>        SharedResource resource = new SharedResource();<br>        WorkerThread thread = new WorkerThread(resource);<br>        thread.start();<br>        <br>        // Main thread waits a bit before reading<br>        Thread.sleep(100);<br>        System.out.println(&quot;Main thread sees count as: &quot; + resource.count);<br>    }<br>}</pre><h4>What Can Go Wrong?</h4><ul><li>The main thread <strong>might still see </strong><strong>count = 0</strong>, even after WorkerThread updated it to 5!</li><li>This happens because <strong>the update might be stored in the CPU cache of the first thread</strong> but not yet written to main memory.</li></ul><h4>Solution: Use volatile to Ensure Visibility</h4><pre>class SharedResource {<br>    volatile int count = 0;  // Ensures changes are visible to all threads<br>}</pre><p>Now, every read/write operation will happen directly in <strong>main memory</strong>, fixing the issue.</p><h3>Problem 2: Race Conditions</h3><h4>What Happens Without Synchronization?</h4><p>A <strong>race condition</strong> occurs when two threads <strong>modify the same variable</strong> at the same time, leading to incorrect results.</p><h4>Example Without Synchronization (Race Condition)</h4><pre>class SharedCounter {<br>    int count = 0;<br>    void increment() {<br>        count++;  // Not thread-safe!<br>    }<br>}<br>public class RaceConditionDemo {<br>    public static void main(String[] args) throws InterruptedException {<br>        SharedCounter counter = new SharedCounter();<br>        Thread t1 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 1000; i++) counter.increment();<br>        });<br>        Thread t2 = new Thread(() -&gt; {<br>            for (int i = 0; i &lt; 1000; i++) counter.increment();<br>        });<br>        t1.start();<br>        t2.start();<br>        <br>        t1.join();<br>        t2.join();<br>        System.out.println(&quot;Final count: &quot; + counter.count);  // Expected: 2000, but result may be less!<br>    }<br>}</pre><h4>What Can Go Wrong?</h4><ul><li>count++ <strong>is not atomic</strong> (it consists of three steps: read, increment, write).</li><li>If <strong>both threads read the same old value</strong>, they might <strong>overwrite each other’s updates</strong>, leading to <strong>incorrect results</strong> (e.g., 1800 instead of 2000).</li></ul><h4>Solution: Use synchronized for Atomic Updates</h4><pre>class SharedCounter {<br>    private int count = 0;<br>    synchronized void increment() {<br>        count++;  // Now thread-safe!<br>    }<br>    int getCount() {<br>        return count;<br>    }<br>}</pre><p>Now, only <strong>one thread at a time</strong> can execute increment(), ensuring correctness.</p><h3>Alternative Solution: Use AtomicInteger for Better Performance</h3><pre>import java.util.concurrent.atomic.AtomicInteger;<br>class SharedCounter {<br>    AtomicInteger count = new AtomicInteger(0);<br>    void increment() {<br>        count.incrementAndGet();  // Atomic and lock-free!<br>    }<br>}</pre><ul><li>AtomicInteger <strong>avoids locking</strong> while ensuring <strong>correct updates</strong>.</li><li>Faster than synchronized, <strong>better for performance</strong> in high-concurrency scenarios.</li></ul><p>Understanding these principles helps in writing efficient and bug-free multi-threaded applications in Java.If I missed any points, let me know your suggestion in the comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e661e098d53" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>