<?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 Vishath Amarasinghe on Medium]]></title>
        <description><![CDATA[Stories by Vishath Amarasinghe on Medium]]></description>
        <link>https://medium.com/@VishathAmarasinghe?source=rss-4ca0328b16f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A7UKiS_nysHr1t4mYVb9mw.png</url>
            <title>Stories by Vishath Amarasinghe on Medium</title>
            <link>https://medium.com/@VishathAmarasinghe?source=rss-4ca0328b16f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:33:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@VishathAmarasinghe/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[Why Your Linux VPS Becomes Unresponsive: Inside the Perfctl Malware Attack]]></title>
            <link>https://medium.com/@VishathAmarasinghe/why-your-linux-vps-becomes-unresponsive-inside-the-perfctl-malware-attack-5771ae2db800?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5771ae2db800</guid>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 14:25:04 GMT</pubDate>
            <atom:updated>2026-03-23T14:25:04.082Z</atom:updated>
            <content:encoded><![CDATA[<p>Everything looked normal until it didn’t. This started with a message from one of my Australian clients. Nothing unusual at first. Just a simple complaint:</p><blockquote><em>“The system becomes unresponsive sometimes… maybe twice a week.”</em></blockquote><blockquote><em>At first, I didn’t think much of it. Production systems slow down. Maybe a memory leak. Maybe a bad query. Maybe just traffic spikes. These are things we deal with all the time.</em></blockquote><blockquote><em>But then he added something that didn’t sit right with me:</em></blockquote><blockquote><em>“When it happens, the entire server becomes unresponsive.”</em></blockquote><blockquote>Not just the application. The <em>entire VPS</em>.</blockquote><p>That’s different.</p><h3>Something Was Off</h3><p>We waited for it to happen again.</p><p>A few days later, it did.</p><p>The application stopped responding. APIs timed out. The frontend couldn’t load data. That part was expected. But when I tried to SSH into the server… it was painfully slow. Almost frozen. No logs. No alerts. No obvious crash. And then something strange happened.</p><p>The moment I finally got into the server, everything became normal again. CPU dropped. System responded. APIs started working.</p><p>Like nothing ever happened.</p><h3>The Pattern</h3><p>At this point, I started paying closer attention.</p><p>This wasn’t random.</p><ul><li>It happened roughly every few days</li><li>Usually, after the server had been running for a couple of weeks</li><li>No clear errors in logs</li><li>No crashes</li><li>No restarts</li></ul><p>And the weirdest part: <strong><em>It always recovered when I logged in.</em></strong></p><p>That was the turning point because systems don’t “heal” just because someone logs in.</p><h3>First Assumption: It’s a Performance Issue</h3><p>I started with the usual checklist.</p><p>Checked memory usage: nothing critical<br>Checked CPU: normal when I logged in<br>Checked disk: fine<br>Checked logs: clean</p><blockquote>Ran: top command</blockquote><p>Nothing suspicious. Looked at running processes, and everything looked normal. At least… on the surface.</p><h3>The Problem With Looking “Live”</h3><p>Here’s the thing I realized later, and this is important: <em>I was only seeing the system </em>after<em> I logged in. </em>Not before. Whatever was happening… was already gone by the time I started investigating. And that made debugging almost impossible.</p><h3>So I Changed Strategy</h3><p>Instead of reacting to the issue, I decided to observe it.</p><p>That’s when I set up:</p><ul><li><strong>Prometheus</strong> for metrics collection</li><li><strong>Grafana</strong> for visualization</li><li><strong>Alerts for CPU, memory, and system load</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3E9q65xJk4QPBMPgxYfPw.png" /><figcaption>Monitoring via Gafana</figcaption></figure><p>I wanted to see what the server was doing <em>when I wasn’t watching</em>. Because clearly, something didn’t want to be seen.</p><h3>The Suspicion</h3><p>While digging through forums and similar issues, I came across something interesting. Multiple developers describing almost the <em>exact same behavior</em>:</p><ul><li>Servers are becoming slow randomly</li><li>High resource usage at idle times</li><li>No clear process showing up</li><li>Everything went back to normal when they logged in</li></ul><p>At first, it sounded like a coincidence. Until I found a name that kept appearing: <strong>Perfctl</strong></p><h3>That Was the First Real Lead</h3><p>Perfctl isn’t a normal process. In fact, it’s designed to look like one. It mimics legitimate Linux system utilities, something you’d easily ignore during a quick check. But underneath, it’s something else entirely. A stealth cryptominer. And what caught my attention the most wasn’t just what it did…</p><p>…but how it behaved.</p><h3>The Behavior That Matched Perfectly</h3><p>This malware has one very specific trait: <em>It stops its activity when a user logs into the system.</em></p><p>Read that again.</p><p>It literally goes silent the moment you start observing the server. Which explains everything I was seeing.</p><ul><li>Server freezes → because CPU is being abused</li><li>I log in → malware pauses</li><li>System looks normal → nothing detected</li></ul><p>It wasn’t that the issue disappeared. It was hiding.</p><h3>What Is Perfctl Malware, And Why Is It So Hard to Catch</h3><p>At this point, I wasn’t 100% sure my server was infected. But the behavior matched <em>too closely</em> to ignore. So I started digging deeper into what exactly this <strong>Perfctl malware</strong> is. And honestly, the more I read… the more uncomfortable it got.</p><h3>A Malware Designed to Look Invisible</h3><p>Perfctl isn’t your typical “loud” malware. It doesn’t crash your system. It doesn’t spam logs. It doesn’t announce itself. Instead, it does something much smarter: <em>It blends in.</em></p><p>The name itself is crafted to look legitimate.</p><ul><li>“perf”: a real Linux performance tool,</li><li>“ctl”: commonly used in system commands</li></ul><p>So when you see something like perfctl or similar process names, your brain just ignores it. That’s exactly what it wants.</p><h3>What It Actually Does</h3><p>At its core, Perfctl is built for one main purpose: <strong><em>To secretly use your server’s resources to make money. </em></strong>It does this by running a <strong>cryptominer</strong> (usually Monero via XMRIG) in the background. But it doesn’t stop there.</p><p>In some cases, it also:</p><ul><li>Uses your server as a <strong>proxy node</strong> (proxy-jacking)</li><li>Opens backdoors for further access</li><li>Communicates through <strong>TOR networks</strong></li><li>Installs hidden components for persistence</li></ul><p>So even if the mining isn’t the main damage… your server is already compromised.</p><h3>The Scariest Part: Its Stealth Behavior</h3><p>This is where things started clicking for me. Perfctl is designed with <strong>evasion as a priority</strong>, not just execution. Some of its key behaviors:</p><h4>1. It Hides When You Log In</h4><p>This is not normal malware behavior. It actively monitors system activity, and when it detects:</p><ul><li>SSH login</li><li>User session activity</li></ul><p>It immediately <em>stops all heavy processes (like mining)</em>,<em> </em>so when you run top or htop… Everything looks clean.</p><h4>2. It Lives in Suspicious Places</h4><p>Instead of staying in obvious locations, it spreads across:</p><ul><li>/tmp</li><li>/usr/bin</li><li>/root/.config</li><li>Hidden directories</li></ul><p>And often:</p><ul><li>Renames itself to look like system files</li><li>Copies itself multiple times</li><li>Deletes original binaries after execution</li></ul><p>So even if you find one… others may still exist.</p><h4>3. It Uses Rootkits</h4><p>This is where it gets serious. Perfctl can modify system utilities like:</p><ul><li>top</li><li>lsof</li><li>crontab</li><li>ldd</li></ul><p>Meaning… <em>The very tools you trust to debug the system can lie to you. </em>Imagine checking CPU usage, and the malware simply hides itself from the output.</p><h4>4. It Targets Idle Systems</h4><p>It doesn’t run all the time aggressively.</p><p>Instead:</p><ul><li>Waits for low activity</li><li>Starts mining heavily</li><li>Consumes CPU quietly</li></ul><p>This explains why: <em>The server becomes slow “randomly”, especially when no one is using it.</em></p><h3>Why This Matched My Case Perfectly</h3><p>At this point, I went back to my original problem.</p><p>Everything started lining up:</p><ul><li>Server freezes after some uptime: same behaviour</li><li>No logs or errors: same behaviour</li><li>CPU issue not visible when checked manually: same behaviour</li><li>System becomes normal when I log in: same behaviour</li></ul><p>That last one… was the biggest confirmation. Because no normal performance issue behaves like that.</p><h3>But I Still Needed Proof</h3><p>Even though everything pointed to Perfctl… I couldn’t just assume. This was a production system. I needed actual evidence before taking action. So I went back to the one thing I had just set up: <strong>Monitoring. </strong>Because, unlike manual checks… Monitoring doesn’t blink. It doesn’t get fooled. And it doesn’t disappear when malware decides to hide.</p><h3>Watching the Server When No One Was Looking</h3><p>Once I had <strong>Prometheus and Grafana</strong> set up, I stopped relying on manual checks.</p><p>Instead of logging in and reacting…</p><p>I let the server tell its story over time.</p><p>I configured dashboards for:</p><ul><li>CPU usage</li><li>Memory consumption</li><li>Disk I/O</li><li>Load average</li></ul><p>And most importantly, I added <strong>alerts</strong>.</p><p>If something unusual happened, I wanted to know <em>before</em> logging in.</p><h3>The First Real Clue</h3><p>A few days passed. Then one evening, I got an alert. High CPU usage.Not slightly high. <strong>Almost maxed out. </strong>I opened Grafana immediately. And there it was. A massive spike. The CPU wasn’t just busy; it was being <em>fully consumed</em> for a long period. Not a quick spike. Not a traffic burst. Sustained usage.</p><h3>But Here’s What Made It Strange</h3><p>There was no corresponding spike in:</p><ul><li>Incoming traffic</li><li>API requests</li><li>Database load</li></ul><p>The system was working hard… but not doing any actual user work.</p><h3>The Moment I Logged In</h3><p>Naturally, I SSH’d into the server.</p><p>And just like before… Everything dropped. CPU usage went back to normal almost instantly. Like someone flipped a switch, that moment confirmed it. <em>This was not a performance issue. </em>This was something actively reacting to my presence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgYBNAyQy15Rf4GFjOvtrg.png" /><figcaption>Snapshot when I logged in to server</figcaption></figure><h3>Catching It in the Act</h3><p>Now I knew one thing: <em>If I log in, I lose the evidence. </em>So I had to think differently. Instead of chasing the problem live… I needed to investigate the system <strong>without disturbing it</strong>.</p><h3>Digging Into Suspicious Areas</h3><p>Based on everything I learned about Perfctl, I started checking common hiding places.</p><p>First stop:</p><pre>sudo ls -lah /tmp</pre><p>Then:</p><pre>sudo ls -lah /usr/bin | grep -i perf</pre><p>And also:</p><pre>sudo ls -lah /root/.config</pre><p>At first glance, nothing obvious jumped out. But that’s expected. This malware doesn’t scream. It whispers.</p><h3>Looking for What Shouldn’t Be There</h3><p>Instead of looking for “known bad files”…</p><p>I started looking for <strong>unusual patterns</strong>:</p><ul><li>Recently modified files</li><li>Strange binary names</li><li>Files without a clear purpose</li></ul><p>Then I ran:</p><pre>sudo find / -type f -mtime -3 2&gt;/dev/null</pre><p>This lists files modified in the last few days. Now things started getting interesting.</p><h3>Suspicious Activity in /tmp</h3><p>The The The /tmp directory stood out. Which makes sense, it’s writable, temporary, and often ignored. Exactly where stealth malware likes to live.</p><p>I noticed:</p><ul><li>Random-looking files</li><li>Unfamiliar binaries</li><li>Files that didn’t belong to any application I deployed</li></ul><p>Some of them didn’t even stay there consistently. They appeared… disappeared… changed names.</p><h3>That Was a Huge Red Flag</h3><p>Because normal applications don’t behave like that.</p><p>They don’t:</p><ul><li>Rename themselves</li><li>Move around the system</li><li>Delete their own binaries</li></ul><p>But malware does.</p><h3>Another Check: Cron Jobs</h3><p>Next, I checked scheduled tasks:</p><pre>sudo crontab -l</pre><p>And also system-wide:</p><pre>sudo ls -lah /etc/cron*</pre><p>Nothing obvious. But here’s the catch: <em>Perfctl is known to hide cron jobs using modified utilities. </em>So even this couldn’t be fully trusted.</p><h3>The Realization</h3><p>At this point, I had enough signals:</p><ul><li>CPU spikes without workload</li><li>Activity disappearing on login</li><li>Suspicious files in /tmp</li><li>No clear visibility through normal tools</li></ul><p>Individually, these might not prove anything. But together? They told a very clear story.</p><h3>The Server Was Compromised</h3><p>Not crashing. Not misconfigured. Not overloaded.<strong>Compromised.</strong></p><h3>Why This Was Dangerous</h3><p>This wasn’t just about performance anymore.</p><p>If it were truly something like Perfctl, then:</p><ul><li>My server was being used for cryptomining</li><li>It could be part of a proxy network</li><li>There might be backdoors installed</li><li>Sensitive data could be at risk</li></ul><p>And worst of all…</p><blockquote><strong><em>It had likely been running for weeks without detection.</em></strong></blockquote><h3>Decision Time</h3><p>At this stage, I had two options:</p><ol><li>Try to remove the malware surgically</li><li>Assume full compromise and rebuild clean</li></ol><p>And honestly… With something this stealthy?</p><p>There’s only one safe answer.</p><h3>Cleaning Up: There Was Only One Safe Option</h3><p>At this point, I had to make a decision.</p><p>Could I try to remove it manually? Maybe.</p><p>But here’s the reality with something like Perfctl:</p><ul><li>It copies itself into multiple locations</li><li>It can modify system binaries</li><li>It may install rootkits</li><li>It can open hidden backdoors</li></ul><p>So even if you remove one part… <em>You can’t be sure what’s still left behind.</em></p><p>And in production, “almost clean” is not acceptable.</p><h3>The Only Safe Approach: Rebuild Everything</h3><p>I decided not to take any risks. Instead of trying to fix the server…</p><p>I informed the client about the case and spun up a new server, routing traffic to that server. Then I started working on this.</p><p>I <strong>rebuilt it from scratch</strong>.</p><p>That meant:</p><ul><li>Fresh VPS</li><li>Fresh OS installation</li><li>Reinstalling all services</li><li>Restoring only <em>clean</em> application data</li></ul><p>No old binaries. No old configs blindly copied. Only what was absolutely necessary.</p><h3>What I Did Differently This Time</h3><p>This incident changed how I approach server security. I didn’t just rebuild, I hardened everything.</p><h4>1. System Updates &amp; Patching</h4><p>First thing:</p><pre>sudo apt update &amp;&amp; sudo apt upgrade -y</pre><p>Especially important for vulnerabilities like:</p><ul><li>Polkit (CVE-2021–4034)</li></ul><p>Because many of these attacks rely on known exploits.</p><h4>2. Locking Down Access</h4><ul><li>Disabled unnecessary ports</li><li>Restricted SSH access</li><li>Used key-based authentication only</li><li>Limited root-level operations</li></ul><h4>3. Restricting Execution in /tmp</h4><p>One of the most important steps:</p><pre>sudo mount -o remount,noexec /tmp</pre><p>This prevents binaries from being executed directly from /tmp , which is a common malware technique.</p><h4>4. Installing Monitoring (Non-Negotiable Now)</h4><p>This time, monitoring wasn’t optional.</p><ul><li>Prometheus running continuously</li><li>Grafana dashboards are always active</li><li>Alerts configured properly</li></ul><p>Because the biggest mistake earlier was: <em>I didn’t have visibility when the issue happened.</em></p><h4>5. Being Careful With What Gets Restored</h4><p>I avoided blindly copying:</p><ul><li>Old system files</li><li>Unknown binaries</li><li>Any executable content</li></ul><p>Only necessary uploads and verified data were restored.</p><h3>The Result</h3><p>After the rebuild:</p><ul><li>No random CPU spikes</li><li>No freezing</li><li>No strange behavior</li><li>The system remained stable over time</li></ul><p>And most importantly: <em>No more “it fixes itself when I log in” moments.</em></p><h3>What I Learned From This</h3><p>This incident changed how I think about server issues because not every problem is a bug. Sometimes… <em>It’s something actively working against you . </em>Here are the biggest lessons I took away:</p><h4>1. If It Disappears When You Look at It, Be Suspicious</h4><p>Normal performance issues don’t behave like that. If a problem vanishes the moment you log in… You’re not debugging anymore. You’re being <em>avoided</em>.</p><h4>2. Monitoring Is Not Optional</h4><p>Logs are not enough. Manual checks are not enough. You need continuous visibility. Because some problems only exist when you’re not watching.</p><h4>3. Don’t Fully Trust System Tools</h4><p>If malware can modify tools like top, lsof, or crontab… Then your debugging tools can lie to you. That’s a dangerous place to be.</p><h4>4. Always assume the worst case in Security</h4><p>If there’s even a small chance your server is compromised, <em>treat it as compromised. </em>Rebuilding may feel extreme…But it’s safer than leaving a hidden backdoor behind.</p><p>What started as a simple “server slowdown” turned into something much deeper.</p><p>A hidden process. A silent attacker.A system that behaved differently when observed. And a reminder that: <em>The most dangerous problems are the ones that don’t want to be found.</em></p><p>If you’re running Linux servers in production… Take this seriously.</p><p>Because if your system:</p><ul><li>Slows down randomly</li><li>Has unexplained CPU spikes</li><li>Becomes normal when you log in</li></ul><p>It might not be a bug. It might be something hiding.</p><p>And by the time you notice it… It may have already been there for weeks.</p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5771ae2db800" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Writing Code to Orchestrating Systems: How AI Agents Are Reshaping Software Engineering]]></title>
            <link>https://medium.com/@VishathAmarasinghe/from-writing-code-to-orchestrating-systems-how-ai-agents-are-reshaping-software-engineering-fe5dc05b9af0?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5dc05b9af0</guid>
            <category><![CDATA[gen-ai-for-software]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agent-development]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 03:19:36 GMT</pubDate>
            <atom:updated>2026-01-01T03:19:36.034Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>2026 didn’t arrive quietly for software engineers. It arrived with agents.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TahQgAkve-cPt6yZEE9xEA.png" /></figure><p>As the new year begins, it’s becoming clear that something fundamental has shifted in how software is built. For years, artificial intelligence sat at the edges of engineering workflows, autocomplete here, code suggestions there, the occasional chatbot answering a Stack Overflow–style question. Useful, but peripheral.</p><p>That era is over.</p><p>According to <em>the 2026 State of AI Agents Report</em> by Anthropic (View the full report <a href="https://cdn.jsdelivr.net/gh/abncharts/abncharts.public.1/abnasia.org/1765455980320_www.abnasia.org.pdf">here</a>), AI agents have moved from experimental tools to production-grade infrastructure. They no longer just help engineers write code. They reason through problems, coordinate tools, make decisions, and execute multi-step workflows autonomously. In short, they are beginning to <strong>orchestrate systems</strong>, not just assist humans.</p><p>And that changes what it means to be a software engineer.</p><h3>From Code-Centric to System-Centric Engineering</h3><p>Traditional software engineering has always been code-first. We designed APIs, wrote services, glued systems together, and manually coordinated workflows across tools and teams. Even as frameworks evolved, humans remained the primary orchestrators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*M7JskV26n4-iLFPi86IcSg.png" /></figure><p>AI agents flip that model.</p><p>More than half of organizations surveyed now deploy agents for <strong>multi-stage workflows</strong>, and a growing share are using them across <strong>cross-functional processes</strong> that span teams, systems, and business functions. These agents don’t wait for a single prompt and stop. They plan, act, verify, and continue, much like a junior engineer executing a task list, but at machine speed.</p><p>For engineers, this means the center of gravity is shifting:</p><ul><li>Less time wiring together repetitive logic</li><li>Less manual coordination between systems</li><li>More time designing <strong>agent-ready architectures</strong></li></ul><p>The job is no longer just to write correct code. It’s to design environments where autonomous systems can safely and reliably operate.</p><h3>Coding Was the Doorway, Not the Destination</h3><p>It’s no surprise that coding was the first place AI agents took hold. Nearly every organization now uses AI in software development, and most have already moved beyond experiments into production.</p><p>What’s more interesting is <em>where the value shows up</em>.</p><p>The report shows productivity gains spread evenly across the entire development lifecycle:</p><ul><li>Planning and ideation</li><li>Research and documentation</li><li>Code generation</li><li>Testing and review</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*x3JRCL7I_xADdrxEkklvdg.png" /></figure><p>This tells us something important: AI agents don’t just make developers type faster. They compress <em>entire timelines</em>. When planning, implementation, and validation all accelerate together, teams don’t just ship sooner, they rethink what’s possible to ship at all.</p><p>In 2026, the competitive advantage won’t come from using AI to write code faster. It will come from using agents to <strong>eliminate coordination overhead</strong> across the lifecycle.</p><h3>Software Is Becoming Agent-Native</h3><p>One of the clearest signals in the report is architectural.</p><p>Most teams are not building agents entirely from scratch. They’re adopting <strong>hybrid approaches</strong>: combining off-the-shelf agent systems with custom components tailored to their domain. This mirrors earlier infrastructure shifts, cloud, containers, and CI/CD, where winning teams focused on composition rather than reinvention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*bF8XCQHEdt6KNIa52_sh-w.png" /></figure><p>For software engineers, this means new design priorities:</p><ul><li>Clear interfaces for agents, not just humans</li><li>Rich context surfaces instead of siloed data</li><li>Systems that tolerate partial execution, retries, and long-running workflows</li></ul><p>Stateless services optimized only for request-response patterns struggle in an agent-driven world. Agents need continuity. They need memory. They need access to tools, data, and permissions, safely governed but not artificially constrained.</p><p>The systems we build in 2026 must assume that <em>non-human actors</em> are first-class users.</p><h3>The Real Bottleneck Isn’t AI, It’s Us</h3><p>One of the most revealing insights from Anthropic’s data is what <em>doesn’t</em> block adoption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*kQUQe0NWkEg8msCDdHU-mQ.png" /></figure><p>It’s not model capability. It’s not a cost.</p><p>The biggest constraints are:</p><ul><li>Fragmented data</li><li>Difficult system integration</li><li>Organizational resistance to workflow change</li></ul><p>AI agents thrive on context. The more fragmented an organization’s knowledge and systems are, the less effective agents become. Every missing document, locked database, or undocumented process is friction not for the AI, but for the humans who designed the system.</p><p>This reframes the role of engineers yet again. Our work increasingly looks like <strong>context engineering</strong>: making institutional knowledge accessible, structured, and safe for autonomous systems to use.</p><h3>From Automation to Delegation</h3><p>Perhaps the most profound shift is psychological.</p><p>Enterprises are no longer merely <em>using</em> AI; they’re <strong>delegating work to it</strong>. Data from millions of real production interactions shows a steady move from augmentation (“help me do this”) to automation (“do this”).</p><p>This doesn’t eliminate engineers. It elevates them.</p><p>As agents handle execution, humans spend more time on:</p><ul><li>System design</li><li>Strategic decision-making</li><li>Edge cases and judgment calls</li><li>Developing new capabilities</li></ul><p>The highest-leverage engineers in 2026 won’t be the fastest coders. They’ll be the ones who know <strong>what to delegate</strong>, <strong>what to supervise</strong>, and <strong>what must remain human</strong>.</p><h3>A New Year, A New Engineering Mindset</h3><p>Every new year invites reflection, but 2026 demands it.</p><p>Software engineering is no longer just about writing programs that respond to requests. It’s about designing ecosystems where intelligent agents can operate responsibly, securely, and at scale.</p><p>The engineers who thrive in this era will:</p><ul><li>Think in workflows, not files</li><li>Design for orchestration, not just execution</li><li>Treat AI agents as infrastructure, not features</li></ul><p>We’re not watching the end of software engineering.</p><p>We’re watching its expansion.</p><p>And as this new year begins, the most important question for engineers isn’t whether AI agents will reshape our field; it’s whether we’re ready to reshape how we build software around them.</p><p>Thank you very much. Let’s meet in another episode.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5dc05b9af0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphRAG-Powered Task Assistant: How to Build a Context-Aware AI Agent]]></title>
            <link>https://medium.com/@VishathAmarasinghe/graphrag-powered-task-assistant-how-to-build-a-context-aware-ai-agent-53a5a72bf029?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/53a5a72bf029</guid>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 01:16:46 GMT</pubDate>
            <atom:updated>2025-07-16T01:16:46.072Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s fast-evolving tech landscape, AI agents are becoming increasingly powerful, especially with the rise of <strong>Large Language Models (LLMs)</strong>. These models now form the backbone of many intelligent systems, from customer service bots to autonomous research assistants.</p><p>But even the most advanced LLMs have their limits, especially when it comes to staying grounded in the right context or accessing up-to-date, structured knowledge. That’s where a powerful new technique comes in: <strong>GraphRAG</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPDNvIjHCC7kbcRpgpbyIQ.png" /></figure><h3>So, what exactly is GraphRAG?</h3><p><strong>GraphRAG</strong> stands for <strong>Graph-enhanced Retrieval-Augmented Generation</strong>. It’s a cutting-edge method designed to enhance how LLMs retrieve, understand, and use external information. By combining traditional retrieval techniques with <strong>knowledge graphs</strong>, GraphRAG helps AI systems become far more <strong>context-aware</strong>, <strong>accurate</strong>, and <strong>intelligent</strong> in their responses.</p><ol><li><strong>Retrieval-Augmented Generation (RAG) </strong>retrieves relevant documents from a knowledge base and feeds them into an LLM to generate responses.</li><li><strong>Knowledge Graphs (KGs) </strong>are structured representations of entities (nodes) and relationships (edges)</li></ol><p><strong>So this diagram will give you a quick insight into what GraphRAG actually</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*5dULegBbUHpVH5gDp6JkfQ.png" /></figure><p>Instead of retrieving raw, unstructured chunks of text, GraphRAG incorporates structured, interconnected knowledge into the LLM’s context window enabling deeper reasoning and better decision-making.</p><p>Now that we have a basic understanding of what <strong>GraphRAG</strong> is, the next logical question is: <strong>Why do we need it?</strong> What exactly is it doing that traditional methods can’t?</p><p>To appreciate what makes <strong>GraphRAG</strong> so powerful, it helps to understand the role of <strong>Large Language Models (LLMs)</strong> in modern AI systems.</p><p>LLMs like GPT, Claude, and LLaMA are trained on massive amounts of text data from books and websites to scientific papers and code. They learn to understand and generate human-like language, making them incredibly useful for a wide range of tasks: answering questions, summarizing content, generating code, and even reasoning over complex topics.But when it comes to <strong>real-world reasoning</strong>, they often stumble. Let’s break down why, it is like that</p><h3>1. Hallucination</h3><p>Imagine you’ve just joined a new software team and you ask a junior developer,</p><p>“How do I deploy our app to the staging environment?”</p><p>Without checking the documentation or confirming with the team, they reply like this</p><p>“Just run <strong>deploy.sh</strong> in the root directory. That script pushes everything to staging.”</p><p>You try it, but it fails, because there is <strong>no such script</strong> or the process is more complex.</p><p>The junior dev wasn’t lying. They just <strong>guessed based on what sounded right</strong>, maybe from another project or what they heard in passing.</p><p>This is what LLMs often do. They <strong>generate plausible-sounding but incorrect answers</strong> because they don’t truly “know” anything. They just predict text based on patterns.</p><p><strong>How GraphRAG Fixes This</strong></p><p>Now, imagine the junior dev has access to a <strong>structured knowledge base</strong> of your project:</p><ul><li>A graph that maps deployment steps:<br> Checkout code -&gt;Build -&gt;Run tests -&gt;Run deploy.sh -&gt;Push to staging</li><li>The dev can query this graph to <strong>get the exact steps and dependencies</strong> before answering.</li></ul><p>So when you ask about deployment, the answer is precise, current, and reliable no guesswork.</p><h3>2. Poor Multi-Step Reasoning</h3><p>Let’s say you ask a cooking assistant,</p><p>“I’m making pasta. What do I do after boiling water and before adding sauce?”</p><p>A regular model might miss the middle step (“cook the pasta”) and jump straight from boiling to saucing.</p><p>This happens because LLMs struggle to <strong>chain steps logically across multiple facts</strong> especially when those steps depend on each other.</p><p><strong>How GraphRAG helps,</strong><br>In a graph, each step is a <strong>node connected to the next</strong>:</p><p>“Boil water -&gt; Cook pasta -&gt; Drain -&gt; Add sauce”</p><p>Now, the model can <strong>walk the chain</strong> and understand what comes before and after. like a mental map.</p><h3>3. Shallow Context Matching</h3><p>Traditional RAG systems use vector search. They find chunks of text that sound similar to your question. But this is like searching for cooking advice and being handed random food blogs because they contain the word “cook.”</p><p>For example, you ask: “How to improve phone battery health?”<br> Traditional RAG gives you a spec sheet about battery capacity.</p><p>It doesn’t understand that <strong>“charging habits”</strong> or <strong>“app background usage”</strong> are <strong>related concepts</strong>.</p><p><strong>How GraphRAG helps:</strong><br> In a graph, related ideas are linked even if they don’t share the same words. So when you ask about battery health, it can follow connections to:</p><ul><li>“charging cycles”</li><li>“screen brightness”</li><li>“app drain behavior”</li></ul><p>You get <strong>semantic understanding</strong>, not keyword matching.</p><p><strong>LLMs are like great storytellers with no memory, logic, or fact-checking.</strong></p><p>GraphRAG is like giving them a <strong>mind map of verified knowledge</strong> so they can reason, recall, and respond better.</p><p>Now that we understand why <strong>GraphRAG</strong> is needed and what problems it solves, let’s take a deeper dive into <strong>how it works</strong> from a technical perspective.</p><p>To understand GraphRAG, let’s first recap how traditional RAG works.</p><h3>Traditional RAG (Retrieval-Augmented Generation)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*lIAkf6q6qS3OOx2CjKY46Q.png" /><figcaption>Traditional RAG Workflow</figcaption></figure><p>In a traditional RAG system, the process begins by converting your query into a vector using an embedding model. This vector is then used to retrieve the top-k most similar text chunks from a vector database, typically flat, unstructured pieces of information. These retrieved chunks are inserted into the prompt provided to a large language model, which then generates an answer based on the combined context of the query and the retrieved documents.</p><p><strong>Traditional RAG retrieves flat text snippets without understanding relationships.</strong></p><h3>GraphRAG (Graph-Enhanced RAG)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*8pdbG9mGPIGJ8nj2t4BVNg.png" /><figcaption>GraphRAG Workflow</figcaption></figure><p>GraphRAG enhances the traditional RAG approach by incorporating a <strong>knowledge graph,</strong> a structured representation of entities (nodes) and their relationships (edges). Instead of relying solely on text similarity, GraphRAG queries both the knowledge graph and the document store. This allows it to retrieve not just isolated text chunks but also <strong>semantically related nodes</strong> and their connections. The result is a richer, more contextual input: structured knowledge from the graph is combined with relevant text documents and fed into the LLM, enabling it to generate responses that are more accurate, interconnected, and context-aware.</p><p>The table below clearly shows the key difference between RAG and GraphRAG</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bb7HNG5JSWQfLNzEANAIdA.png" /></figure><p>Now that we understand how GraphRAG works, the next step is to connect it to a broader concept: <strong>AI agents</strong>.</p><h3>Connecting the Dots: GraphRAG and AI Agents</h3><p>AI agents are software entities designed to autonomously perform tasks, make decisions, and interact with users or environments. To be truly effective, they need memory, reasoning, and contextual understanding beyond simple pattern matching.</p><p>Traditional AI agents that rely solely on language models or flat retrieval struggle with:</p><ol><li>Remembering previous interactions</li><li>Understanding complex relationships between concepts or tasks</li><li>Planning multi-step actions based on evolving context</li></ol><p><strong>This is where GraphRAG becomes a powerful enabler.</strong></p><p><strong>How GraphRAG Empowers AI Agents:</strong></p><ol><li>Structured Memory<br>GraphRAG equips agents with a knowledge graph, a structured memory that stores entities, concepts, and their relationships. Unlike plain text retrieval, this graph preserves the connections between information essential for meaningful reasoning.</li><li>Context-Aware Reasoning<br>By querying the knowledge graph, agents can retrieve not just isolated facts but connected knowledge. This allows multi-hop reasoning, enabling agents to understand dependencies (e.g., “Task A must finish before Task B starts”).</li><li>Explainability &amp; Traceability<br>Since knowledge is stored in graphs, agents can trace their reasoning paths and explain why they suggested a particular action, crucial for trust in high-stakes domains like healthcare or finance.</li><li>Dynamic Learning &amp; Planning<br>Agents can update their graph memory over time, adding new nodes and relationships as they learn or observe new data. This evolving knowledge base supports long-term planning and adaptation.</li><li>Better Prompt Construction<br>GraphRAG helps build focused, relationship-rich prompts for the LLM, improving output relevance and reducing hallucination.</li></ol><p>So let’s build a simple Task-Oriented AI Agent with GraphRAG. So this kind of Agent is useful for personal assistants, project management tools, or workflow automation, where understanding task order and dependencies is critical.</p><h3>A Simple Task-Oriented AI Agent with GraphRAG</h3><p>For this task, I’m using Python as my core programming language and using OpenAI’s GPT model as the LLM for the Agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKNECyfNeDbDhyYusfnnkg.png" /></figure><p>From the above code snippet I provide my OpenAI key for the LLM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4h1gs1pDsjvJNSsXGPP7XA.png" /></figure><p>Let’s walk through how this simple AI agent uses GraphRAG principles to suggest the next best task based on what you’ve just completed.</p><p>We define a list of <strong>triplets</strong> representing task dependencies like “Write draft -&gt; Review draft”. These triplets are then added to a directed graph (nx.DiGraph()) using networkx, where each <strong>node</strong> is a task and each <strong>edge</strong> represents a dependency or sequence (“precedes”)</p><p>The result is a lightweight <strong>task flow graph</strong> the agent can reason over.</p><p>When a user provides the current task they’ve completed, the agent queries the graph to find the next logical task(s). It then sends this context, along with the user’s input, to OpenAI’s GPT-4 model. The model responds with a suggestion for what to do next and explains why, grounded in the structure of the task graph. The final response is neatly printed line by line using text wrapping for better readability.</p><p>By now, you should have a solid understanding of how <strong>GraphRAG</strong> enhances traditional RAG systems and why it’s such a valuable tool for building smarter, more context-aware <strong>AI agents</strong>. From structured knowledge retrieval to deeper reasoning capabilities, GraphRAG brings us one step closer to agents that don’t just respond but truly understand.</p><p>In this article, we explored how GraphRAG works under the hood, why it matters, and how it can be applied to create task-oriented agents capable of handling real-world workflows with intelligence and adaptability.</p><p>In the next article, we’ll take things further by exploring <strong>realistic, production-level AI agents</strong> powered by GraphRAG</p><p>Thank you!</p><p>Key Resource: <a href="https://microsoft.github.io/graphrag/">https://microsoft.github.io/graphrag</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a5a72bf029" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Chatbots to Autonomous Agents: Building Multi-Step Reasoning Systems with LLMs]]></title>
            <link>https://medium.com/@VishathAmarasinghe/from-chatbots-to-autonomous-agents-building-multi-step-reasoning-systems-with-llms-a0e3ac6402cc?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0e3ac6402cc</guid>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Fri, 04 Jul 2025 09:57:18 GMT</pubDate>
            <atom:updated>2025-07-04T09:57:18.702Z</atom:updated>
            <content:encoded><![CDATA[<p>Most chatbots can answer a single question, but imagine one that books flights, compares prices, sends emails, or writes code all in one. In this article, we’ll move beyond static prompts and explore how large language models (LLMs) can reason, plan, and act in multiple steps, just like a human assistant.</p><p>We’ll dive into practical examples and show you how to build your own multi-step reasoning agent using ChatGPT APIs, LangChain, and popular agent architectures like ReAct and AutoGPT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AegzWo6Z49v-vuMFvj4qHw.png" /></figure><h3><strong>What is an AI Agent?</strong></h3><p>An <strong>AI agent</strong> is an intelligent system capable of perceiving its environment, making decisions, and taking actions to achieve specific goals, often autonomously. Unlike traditional chatbots that operate based on simple rule-based responses or single-turn interactions, AI agents are designed to:</p><p><strong>Perceive</strong>: Understand context and tasks through language inputs or sensory data.</p><p><strong>Reason</strong>: Break down complex tasks, make plans, and decide what tools or steps are needed.</p><p><strong>Act</strong>: Execute those plans, such as performing searches, writing files, sending messages, or executing code.</p><p><strong>Learn/Adapt</strong>: Retain memory of past interactions to improve future responses or decisions.</p><p><strong>Example:</strong> A chatbot answers, ‘The weather is sunny.’</p><p>An <strong>agent</strong> not only finds that answer but may also add, “Would you like me to suggest nearby outdoor activities based on the forecast?”</p><p>This shift from reactive Q&amp;A systems to proactive, autonomous decision-makers is why AI agents are at the forefront of next-generation AI applications.</p><h3><strong>Chatbots vs Autonomous Agents</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSUHEHnlvMYHDFzswry9Fg.png" /></figure><p><strong>More explanations about the above features</strong></p><p><strong>Single-turn</strong>: Chatbots typically work with single-prompt response cycles. Autonomous agents track multiple interactions and contexts. <em>A chatbot may only answer “Your appointment is at 3 PM.” An agent may say, “You’re free at 2 PM, shall I reschedule to avoid the clash?”</em></p><p><strong>Tool Use</strong>: Agents can invoke tools like calculators, web search, file access, or even APIs. AutoGPT can use a browser or file system to search, save, or manipulate data. LangChain tools enable this.</p><p><strong>Memory</strong>: Autonomous agents can recall previous facts or learn across sessions. “Remember, my favorite color is blue.” → “Your favorite color is blue, right?” (next day)</p><p><strong>Planning</strong>: Agents can create subgoals and a sequence of steps to reach a target outcome. “Book me a flight and hotel for Tokyo under $1,000.”</p><p><strong>Self-correction</strong>: Agents can retry failed steps or refine plans. If a search fails or an API call is invalid, agents can adapt and rerun.</p><p>Autonomous agents are systems powered by LLMs that can interact with tools, retain memory over sessions, make decisions, and adjust based on outcomes.</p><h3><strong>Agent Architectures</strong></h3><h4><strong>ReAct (Reason + Act)</strong></h4><p>A framework where an agent alternates between reasoning (thinking) and taking action (using tools).</p><p>The agent starts with a thought like “I need more information”, performs a search, reflects on the result, and only then answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*sBkEnAgg1oAQzdxdvz8Qtg.png" /><figcaption>ReAct Agent</figcaption></figure><p>Below is one example of ReAct agent.</p><p><strong><em>Thought</em></strong><em>: I need to know the latest AI research.</em></p><p><strong><em>Action</em></strong><em>: Use a web search tool.</em></p><p><strong><em>Observation</em></strong><em>: Found a paper on the Recurrent Memory Transformer.</em></p><p><strong><em>Thought</em></strong><em>: This looks relevant.</em></p><p><strong><em>Final Answer</em></strong><em>: The latest AI research focuses on recurrent memory in transformers.</em></p><p>We will write a simple autonomous agent with ReAct Agent architecture.</p><h4><strong>AutoGPT</strong></h4><p>An autonomous system that uses LLMs to complete a high-level goal with minimal human input.</p><p>You give it a goal like “Build a website.” AutoGPT creates subtasks and executes them using tools like browser, file system, and code execution. It also evaluates its own results and adapts.</p><p>Below is an example of AutoGPT.</p><p>The goal is to “Create a marketing site for a bakery.” Subtasks Research competitors → Generate homepage content → Save HTML file → Open browser to preview</p><h4><strong>BabyAGI</strong></h4><p>A lightweight task management loop built on LLMs that continuously creates, executes, and reprioritizes tasks.</p><p>Starts with a goal, generates tasks, executes one, and creates new tasks based on outcomes. Keeps track of progress and iterates.</p><p>Below is an example of babyAGI, and the Goal is “Grow my newsletter audience.”</p><p><strong>Step 1</strong>: Analyze best-performing posts</p><p><strong>Step 2</strong>: Generate email content</p><p><strong>Step 3</strong>: Schedule posts</p><p><strong>Step 4</strong>: Add new task: “Create a Twitter thread on email growth”</p><p>We will discuss more about BabyAGI and AutoGPT in the next articles.</p><p><strong>So let&#39;s build a full, advanced autonomous agent with memory, file read-write capabilities, and tooling.</strong></p><p><strong>Note: I’m using Python to build the autonomous Agent.</strong></p><p>First, you need to install the following packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFyROVXlrH5UTZjaPY39FQ.png" /></figure><p>Then you need to have an OpenAI key and a Tavily API key. You can get these from <a href="https://platform.openai.com/">https://platform.openai.com</a> and <a href="https://app.tavily.com/">https://app.tavily.com</a>. After that, you need to import them into your environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBPqjJ65cj6sbsGMYVlRMg.png" /></figure><p>Then you can use the code snippet below to build your autonomous agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14wVFcQAiCX6YiBCkP1p-g.png" /></figure><p>Just for now, I hardcoded the query; you can use the input field to get the query from the user.</p><p>Below is the simple answer for my query of “search what is the capital of Sri Lanka and calculate 23 * 57.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pg2nHGgYazgXRYZKaYxPtw.png" /><figcaption>Answer</figcaption></figure><p>This AI agent combines the power of OpenAI’s GPT model with a set of specialized tools to handle multiple types of tasks in one conversation. At its core, the agent uses the ChatOpenAI language model to understand and reason about user queries. However, instead of just responding with text, it can decide to use external tools like a web search engine or a Python interpreter to fetch up-to-date information or perform calculations. This multi-tool setup allows the agent to perform complex, multi-step tasks rather than just single-turn Q&amp;A.</p><p>The agent includes four key tools: a web search tool powered by Tavily to look up current information online, a Python interpreter to execute code and do math or logic operations, and two simple file tools that let the agent read from and write to files on the local system. When a user inputs a query, the agent first tries to understand what’s being asked and then plans which tools it needs to call to fulfill the request. For example, if the query asks for a fact plus a calculation, the agent may first use the web search to get the fact and then run the calculation in Python.</p><p>Under the hood, the agent uses an architecture called “ZERO_SHOT_REACT_DESCRIPTION,” which means it reasons step-by-step and decides which tool to use without any prior training on specific tasks. It thinks (“I need to search the web for this”), acts (calls the web search tool), observe the results, and then decides the next step (for example, “Now I need to do a calculation”). This back-and-forth continues until the agent is confident it has the final answer, which it then returns to the user.</p><p>Overall, this approach enables the AI to act more like a helpful assistant that can use external resources and tools dynamically, rather than just relying on static knowledge baked into the language model. The inclusion of file reading and writing also means the agent can save or retrieve information persistently, making it useful for tasks like note-taking or data management. This code example demonstrates how combining language models with versatile tools opens the door to building advanced, multi-functional AI agents that go far beyond simple chatbots.</p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0e3ac6402cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Web Applications: A Developer’s Guide to Throughput, Latency, and Bandwidth]]></title>
            <link>https://medium.com/@VishathAmarasinghe/optimizing-web-applications-a-developers-guide-to-throughput-latency-and-bandwidth-03d626ab61aa?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/03d626ab61aa</guid>
            <category><![CDATA[bandwidth]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 12:53:15 GMT</pubDate>
            <atom:updated>2025-04-15T12:53:15.109Z</atom:updated>
            <content:encoded><![CDATA[<p>When building or using a web application, performance is everything. Whether it’s a social media platform, an e-commerce site, or a cloud-based dashboard, users expect a fast, smooth experience. But behind the scenes, three invisible forces are constantly at play: latency, throughput, and bandwidth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sC7f_9UqOcR2USAb7CRbiA.png" /></figure><p>Understanding these three concepts is key to optimizing web performance. In this article, we’ll break down what they are, how they’re different, and how they affect web apps in the real world.</p><h3>Latency</h3><p><strong>Latency</strong> is the time it takes for a request to travel from the client (browser) to the server and back again. It’s often called as ‘lag’ and is measured in <strong>milliseconds (ms)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*wNqwD4_lUeUIZi2xNbmnNw.png" /><figcaption>Life Cycle of Latency</figcaption></figure><p><strong>Why it matters:</strong></p><ul><li>High latency means users wait longer for content to load.</li><li>Especially noticeable in <strong>real-time apps</strong> like online games, live video.</li></ul><p>A simple example is, when you click a button on a website and it takes 200ms before anything happens, that 200ms is your latency. Even if your internet is fast, if the server is far away or under heavy load, latency increases.</p><h3>Reducing Latency: A Developer’s Perspective</h3><p>Reducing latency in web applications requires understanding the full lifecycle of a request from the time a user initiates it to when the server sends back a response. Several key factors contribute to latency, including backend processing time, the physical distance between client and server, the number of network routing hops, and slow database queries. To address these, developers can apply a range of techniques.</p><p>One of the most effective strategies is using <strong>Content Delivery Networks (CDNs)</strong>. CDNs like Cloudflare and Amazon CloudFront cache and serve static assets (HTML, JavaScript, CSS, images, and videos) from locations closer to the user. This reduces DNS lookup time, connection setup time, and latency caused by geographical distance.</p><p>Next, optimizing <strong>backend logic</strong> plays a crucial role. Even if your network is fast, inefficient code in your backend services can become a bottleneck. Developers should profile API endpoints using tools such as Spring Boot Actuator and Micrometer for Java, clinic.js and express-response-time for Node.js, or MiniProfiler and Application Insights for .NET. Common areas to optimize include removing expensive loops, avoiding blocking synchronous calls, reducing redundant service calls</p><p>In terms of data handling, <strong>database query optimization</strong> is essential. Developers should ensure proper indexing, avoid unnecessarily complex joins, and implement caching layers like Redis or Memcached to reduce load on the database for frequently accessed data.</p><p><strong>Server location</strong> also impacts latency. Hosting your application in multiple regions (e.g., using AWS or Azure availability zones) and leveraging geo-based DNS routing (such as Amazon Route 53 or Cloudflare Load Balancer) ensures users are directed to the nearest server, minimizing travel time for requests.</p><p>Upgrading your application to support <strong>HTTP/2 or HTTP/3</strong> can drastically improve performance by reducing connection overhead. HTTP/2 enables multiplexing, allowing multiple resources to load over a single connection more efficiently. Finally, <strong>TLS handshake optimizations</strong> can reduce the delay during secure connection setup. Enabling <strong>TLS 1.3</strong> and configuring <strong>session reuse</strong> can minimize the need for full handshakes on repeat connections, cutting down unnecessary overhead.</p><p>Altogether, these techniques from caching and server logic to protocols and network architecture empower developers to significantly reduce latency and deliver faster, smoother user experiences.</p><h3>Bandwidth</h3><p><strong>Bandwidth</strong> is the maximum amount of data that can be transmitted per second over a network connection. It’s measured in <strong>megabits per second (Mbps)</strong> or <strong>gigabits per second (Gbps)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-drDbza58qxknXm_ODzcw.png" /><figcaption>Source: <a href="https://www.liquidweb.com/">https://www.liquidweb.com</a></figcaption></figure><p><strong>Why it matters:</strong></p><ul><li>It determines how <strong>much</strong> data can flow at once.</li><li>Limited bandwidth slows down large file downloads, video streaming, or image-heavy web pages.</li></ul><p>If your app loads a 10MB video but your bandwidth is only 5 Mbps, it will take about 16 seconds just to load the video fully (because 10 MB = 80 Mb; 80 ÷ 5 = 16s).</p><h3>Optimizing Bandwidth for Web Applications</h3><p>When developing web applications, it’s crucial to reduce bandwidth usage to ensure fast load times, especially for users on slow or mobile networks. High bandwidth consumption often occurs due to large <strong>images, unminified JavaScript and CSS</strong>, excessive third-party libraries (such as fonts and plugins), and heavy <strong>API payloads</strong>. These factors can significantly slow down page loading, increase server load, and degrade the overall user experience. Developers need to adopt several strategies to address these issues and optimize bandwidth.</p><p>One of the most important strategies is to <strong>compress and optimize images</strong>. Large image files can dramatically increase the amount of data transferred to users, so it’s essential to use modern image formats like <strong>WebP</strong>, <strong>AVIF</strong>, or <strong>JPEG XL</strong>. These formats offer significantly smaller file sizes without compromising on quality. Additionally, developers can use <strong>responsive image techniques</strong> (e.g., the &lt;picture&gt; tag or srcset) to serve images that are appropriately sized for different screen resolutions and device types, reducing unnecessary data transfers. Tools like <strong>ImageMagick</strong>, <strong>TinyPNG</strong>, <strong>Squoosh</strong>, and <strong>sharp</strong> (Node.js) can help automate and streamline the compression process, especially when integrated into build pipelines like <strong>Webpack</strong>.</p><p>Next, <strong>minimizing and bundling JavaScript and CSS</strong> is key to reducing unnecessary bandwidth usage. Developers should leverage techniques such as <strong>tree shaking</strong> and <strong>code splitting</strong> to eliminate unused code and only load the necessary parts of the application. Bundling JavaScript and CSS files helps reduce the number of HTTP requests, but it’s important to avoid creating giant bundles, as they can still impact performance. Instead, use <strong>code splitting</strong> to load only the code needed for the current view. Popular bundling tools like <strong>Webpack</strong>, <strong>Rollup</strong>, and <strong>Vite</strong> can assist with this process. Additionally, tools like <strong>Terser</strong> and <strong>UglifyJS</strong> for minifying JavaScript, and <strong>CSSNano</strong> and <strong>PurgeCSS</strong> for optimizing CSS, are crucial in minimizing file sizes.</p><p>Another powerful method for optimizing bandwidth is enabling <strong>compression</strong> for assets like HTML, CSS, JavaScript, and JSON. Developers should configure their servers (e.g., <strong>Nginx</strong>, <strong>Apache</strong>, or <strong>Node.js Express</strong>) to use <strong>Gzip</strong> or <strong>Brotli</strong> compression. Brotli, in particular, offers superior compression ratios for most types of files compared to Gzip, reducing the overall size of assets sent over the network. Tools like <strong>GTmetrix</strong>, <strong>WebPageTest</strong>, and Chrome’s <strong>DevTools Network tab</strong> can help developers test and verify whether their compression settings are working effectively.</p><p>For API-heavy applications, <strong>reducing API payload sizes</strong> can significantly save bandwidth. Rather than returning large datasets with every API response, developers can adopt strategies like <strong>pagination</strong> and <strong>field selectors</strong> (such as in <strong>GraphQL</strong> or <strong>REST APIs</strong>) to only send the data that’s necessary. For instance, instead of including complete user profiles with each comment, developers can return just the user ID and display name. This minimizes the data sent and makes responses faster. Additionally, compressing API responses using <strong>Gzip</strong> or <strong>Brotli</strong> can further reduce the payload size. For Node.js, <strong>express-compression</strong> and for Spring Boot, GZIP filters can be used to compress responses before they’re sent to the client.</p><p>To improve efficiency even further, <strong>lazy loading</strong> and <strong>code splitting</strong> of resources like images, videos, and JavaScript files is essential. Lazy loading ensures that assets are only downloaded when they are needed. For example, images can be loaded only when they come into view on the page (using the loading=&quot;lazy&quot; attribute), or JavaScript chunks can be dynamically imported as required (e.g., in <strong>React</strong>, <strong>Vue</strong>, or <strong>Angular</strong>). This reduces the initial payload and speeds up the load time of the application. An example of dynamic import in React would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_i0LYTk5gBNohc6b-kjcA.png" /><figcaption>Lazy loading example</figcaption></figure><p>By focusing on these key areas — <strong>image compression</strong>, <strong>JavaScript and CSS minification</strong>, <strong>API optimization</strong>, <strong>lazy loading</strong>, and <strong>reducing third-party scripts </strong>developers can significantly reduce bandwidth usage, leading to faster page loads, reduced server costs, and an overall improved user experience.</p><h3>Throughput</h3><p><strong>Throughput</strong> is the <strong>actual amount of data</strong> successfully transferred over a network in a given time. It’s often <strong>less than bandwidth</strong> due to network congestion, protocol overhead, or hardware limitations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*AFDQAH6YplvswRRbXLCmng.png" /><figcaption>Source: <a href="https://www.rfwireless-world.com/">https://www.rfwireless-world.com</a></figcaption></figure><h3>Why it matters:</h3><ul><li>Throughput is the <strong>real performance</strong> your app is getting.</li><li>Low throughput can result in slow page loads and buffering, even if the bandwidth is high.</li></ul><p>Let’s discuss this with an analogical example. Imagine a highway with 5 lanes (bandwidth), but due to accidents and traffic (congestion), only 2 lanes are usable. That’s your <strong>throughput </strong>lower than the max potential.</p><h3>Optimizing throughput for Web Applications</h3><p>One important way developers can improve web application throughput is by adopting modern HTTP protocols like HTTP/2 and HTTP/3. Unlike the older HTTP/1.1, which only handles one request per connection, HTTP/2 allows multiple requests and responses to be sent simultaneously over a single connection using a technique called multiplexing. This drastically reduces waiting time, especially when a page requires many assets like JavaScript, CSS, or images. HTTP/3 goes even further by using the QUIC protocol, which is built on UDP instead of TCP. This change significantly cuts down on connection setup time, making it especially beneficial for real-time applications like video conferencing or chat.</p><h3>Overall Idea</h3><p>Optimizing web applications for latency, bandwidth, and throughput is essential for delivering fast, reliable, and responsive user experiences. Each of these factors plays a distinct role. latency impacts how quickly a request is acknowledged, bandwidth limits how much data can be transferred, and throughput reflects the actual data delivery rate under real-world conditions. By understanding and addressing each one through strategies like CDN usage, protocol upgrades (HTTP/2, HTTP/3), efficient backend and database handling, asset compression, and intelligent loading techniques, developers can drastically improve performance. In an era where milliseconds matter, these optimizations not only enhance usability but also strengthen user retention, search engine rankings, and overall business success. For developers, mastering these performance fundamentals isn’t just a technical choice.it’s a competitive advantage.</p><p>Lets discuss tools that we can use for web optimization in the next article.Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03d626ab61aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Distributed Transactions in Microservices]]></title>
            <link>https://medium.com/@VishathAmarasinghe/handling-distributed-transactions-in-microservices-ace46b19043a?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ace46b19043a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 14:24:49 GMT</pubDate>
            <atom:updated>2025-03-01T14:24:49.518Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore some fundamental concepts of distributed transactions in a microservices architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xeHF2hJQcDeftN98gFM9Q.png" /></figure><h3>What is a Microservice?</h3><p>A microservice is a small, independent service that performs a specific function within a larger system. Instead of building a single, large application (monolith), we break it down into smaller, self-contained services that work together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*CquR7w3GSI0Mvr2qCkootQ.png" /><figcaption>Microservice Architecture</figcaption></figure><p>Example: Online Store</p><p>Consider an online store. Instead of developing it as one large application, we can divide it into separate services that operate independently but work together to form a complete system:</p><ul><li>Order Service — Handles order processing.</li><li>Payment Service — Manages payments and transactions.</li><li>Inventory Service — Tracks and updates stock levels.</li></ul><h3>What is a Transaction?</h3><p>A transaction is a sequence of actions that must either all succeed or all fail to maintain data consistency.</p><h4>Real-World Example</h4><p>Imagine purchasing a product from an online store using a credit or debit card. The transaction involves multiple steps:</p><ol><li>The order is placed.</li><li>The payment is processed, and money is deducted from the bank account.</li><li>The inventory is updated to reflect the purchased item.</li></ol><p>If any of these steps fail, the entire transaction must be rolled back to prevent inconsistencies. For example, if the order is processed and payment is deducted, but the inventory update fails, the system must undo the entire transaction to ensure accuracy.</p><h3>What is a Distributed Transaction?</h3><p>A <strong>distributed transaction</strong> is a transaction that involves multiple microservices and databases. If one part of the transaction fails, we must ensure that the entire process is either completed successfully or rolled back to maintain data consistency.</p><p>Example: Online Order Processing</p><p>Consider an online order where multiple services work together:</p><ol><li><strong>Order Service</strong> creates an order.</li><li><strong>Payment Service</strong> charges the customer.</li><li><strong>Inventory Service</strong> updates stock.</li><li><strong>Shipping Service</strong> prepares the delivery.</li></ol><p>Problem: What if the <strong>Payment Service fails</strong> after the order is created?<br>We don’t want an order to exist without a successful payment. This is why distributed transactions are essential — they help maintain consistency across all services.</p><h3><strong>Why Are Distributed Transactions Difficult?</strong></h3><p>In a <strong>monolithic system</strong>, a single database manages all operations, making transaction handling simpler. However, in <strong>microservices architecture</strong>, each service has its own database, leading to challenges such as:</p><ol><li><strong>Undoing previous steps</strong> — If one step fails, how do we roll back the changes already made?</li><li><strong>Ensuring consistency</strong> — How do we make sure all services have the correct data?</li><li><strong>Handling failures</strong> — What if a service crashes in the middle of the transaction?</li></ol><p>To address these challenges, we need specialized approaches to handle distributed transactions effectively.</p><h3>When Do We Need Distributed Transactions?</h3><p>We need distributed transactions whenever a <strong>business process spans multiple microservices</strong>, and all steps must be consistent. If one step fails, we must either undo previous actions or apply corrective measures to prevent issues like incomplete orders or missing payments.</p><p>Example 1: <strong>E-commerce Order Processing</strong></p><p>Imagine buying a phone online. This process involves multiple microservices:</p><ol><li>Order Service — Creates the order.</li><li>Payment Service — Charges your credit card.</li><li>Inventory Service — Updates stock.</li><li>Notification Service — Sends an order confirmation email.</li></ol><p><strong>Problem: </strong>What if the <strong>payment fails</strong> after the order is created? The system would have an order, but no payment was made.</p><p><strong>Solution: </strong>The system must <strong>automatically cancel</strong> the order (rollback) to prevent inconsistencies.</p><p>Example 2: <strong>Banking Transactions</strong></p><p>Imagine transferring <strong>$100</strong> to a friend using a banking app. The process involves:</p><ol><li>Your Bank Service — Deducts $100 from your account.</li><li>Receiver’s Bank Service — Adds $100 to your friend’s account.</li></ol><p><strong>Problem: </strong>What if <strong>your bank deducts the money, but the receiver’s bank fails</strong> to add it? Your money is gone, but your friend didn’t receive it.</p><p><strong>Solution: </strong>The system must <strong>refund</strong> your $100 if the transaction fails.</p><h3><strong>How to handle distributed transactions.</strong></h3><h4>1. Two-Phase Commit (2PC)</h4><p>This approach ensures that all involved services agree before executing a transaction. It works like a <strong>group decision-making process</strong> — if everyone agrees, the action proceeds; otherwise, it’s canceled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*dPb7MzNJ0VIBdYVoZp6UwQ.png" /><figcaption>2-phase commit</figcaption></figure><p>Example: <strong>Sending Money Between Two Banks</strong></p><p>Imagine you have <strong>$1000</strong> in Bank Account A and want to transfer it to Bank Account B.</p><p><strong>Step 1: Ask for Confirmation</strong></p><p>The system asks both banks, <strong>“Are you ready to process this transaction?” </strong>Both banks verify if the transfer can proceed.</p><p><strong>Step 2: Proceed or Cancel</strong></p><ul><li>If both banks say <strong>“Yes”</strong>, the system completes the transaction.</li><li>If either bank says <strong>“No”</strong>, the transaction is <strong>canceled entirely</strong> to prevent inconsistencies.</li></ul><p>let’s check what are the advantages and disadvantages of using this method.</p><p><strong>Advantages</strong></p><p>· Ensures <strong>strong consistency</strong> (every step must succeed).</p><p>· Ideal for <strong>banking and financial transactions</strong> where accuracy is crucial.</p><p><strong>Disadvantages</strong></p><p>· Slows down performance because it <strong>waits for confirmation</strong> from all services.</p><p>· <strong>Not suitable for high-speed systems</strong> like e-commerce or real-time applications.</p><h4><strong>2. Saga Pattern</strong></h4><p>Instead of completing everything at once, Saga breaks a transaction into smaller steps. If something fails, previous steps are <strong>rolled back</strong> to maintain consistency.</p><p>Example: Ordering a Phone Online</p><p>Step 1 — Order Service creates the order.</p><p>Step 2 — Payment Service charges your card.</p><p>Step 3 — Inventory Service updates stock.</p><p>Problem:What if the payment fails after the order is created?</p><p>Solution: The system cancels the order (rollback).</p><p><strong>Two Ways to Use the Saga Pattern:</strong></p><ol><li><strong>Choreography — “Each Service Talks to the Next One”</strong></li></ol><ul><li>Each service <strong>automatically triggers the next step</strong> when its job is done.</li><li>Simple, decentralized, no need for a central controller are the advantages.</li><li>Can get complicated when many services interact is one of the main disadvantages.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*oXqrrdjvALNJJQ1dPGSqWQ.png" /><figcaption>Saga pattern in Choreography</figcaption></figure><p><strong>2. Orchestration — “A Central Controller(API Gateway) Manages Everything”</strong></p><ul><li>A central service/API gateway controls the transaction steps and ensures rollback if needed.</li><li>More control, easier debugging are some advantages</li><li>Can introduce a single point of failure if the orchestrator crashes is a disadvantage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*tHeAUl8ob9Ndb9RpOPXQ0w.png" /><figcaption>Saga pattern in Orchestration</figcaption></figure><p>The saga pattern is best suitable for <strong>E-commerce, travel bookings, food delivery</strong> (where rollbacks are manageable).</p><p>Not ideal if rollback logic is too complex (reversing multiple interdependent actions) is the main drawback in saga pattern.</p><h4>3. Eventual Consistency with Event-Driven Architecture</h4><p>In an <strong>event-driven architecture</strong>, services communicate by publishing and subscribing to events. When a service updates data, it <strong>emits an event</strong>, and other services <strong>listen</strong> to it and update their state accordingly.</p><p>How It Works:</p><ol><li>A service changes data (a user makes a purchase).</li><li>It publishes an event (“Order Placed”).</li><li>Other services subscribe and respond accordingly (e.g., Payment Service charges the customer, Inventory Service updates stock).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*0njQhu4-4Mz6NXaD9NvC-w.png" /><figcaption>Handling distributed transactions with Event driven architecture</figcaption></figure><p><strong>Advantages</strong></p><p>· Highly scalable — Services operate independently.</p><p>· Flexible — New services can subscribe without modifying existing ones.</p><p><strong>Disadvantages</strong></p><p>· Temporary inconsistency — Some services may update later than others.</p><p>· Harder to debug — Since events flow asynchronously, tracking failures can be complex.</p><h4>4. Compensation-Based Transactions</h4><p>In this method, if something goes wrong, the system <strong>manually compensates</strong> by undoing previous actions.</p><p><strong>Advantages</strong></p><p>· Works well for refunds, failed payments, and order cancellations.</p><p>· Helps fix inconsistencies after a failure.</p><p><strong>Disadvantages</strong></p><p>· Doesn’t work for irreversible actions (e.g. if a physical product is already shipped, it can’t be “undone”).</p><p>· Requires additional logic to track and execute compensation steps.</p><h3><strong>Choosing the Right Approach for Distributed Transactions</strong></h3><p>Handling distributed transactions in a microservices architecture requires careful consideration of consistency, performance, and fault tolerance. Based on the business needs and technical constraints we need to choose the most appropriate one.</p><ul><li>Two-Phase Commit (2PC) ensures strong consistency but impacts performance and scalability.</li><li>Saga Pattern provides flexibility and resilience, making it ideal for business workflows that can tolerate compensating transactions.</li><li>Event-Driven Architecture enables loosely coupled services but requires careful handling of eventual consistency.</li><li>Compensation-Based Transactions offer a practical way to handle failures but require additional logic to reverse actions.</li></ul><p>In real-world applications, businesses often combine multiple approaches to balance consistency and performance. For example, financial transactions may use <strong>2PC</strong>, while e-commerce platforms favor <strong>Sagas or Event-Driven Architectures</strong> for scalability.</p><p>By understanding these techniques, we can design robust microservices that maintain data integrity without sacrificing performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ace46b19043a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking the Java Memory Model: A Simple Guide to Multi-Threading]]></title>
            <link>https://medium.com/@VishathAmarasinghe/cracking-the-java-memory-model-a-simple-guide-to-multi-threading-b6eb86c6ff5c?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6eb86c6ff5c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[threading-in-java]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 17:06:04 GMT</pubDate>
            <atom:updated>2025-02-20T17:06:04.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAb9CMWXMlRfsUudCtq01Q.png" /></figure><p><strong>Multithreading</strong> is a powerful technique in programming that allows multiple tasks to run at the same time. If you’re new to Java threads and multithreading, you can check out my previous articles where I explain threads and their lifecycle in a simple way.</p><p><a href="https://medium.com/@VishathAmarasinghe/mastering-java-threads-part-1-2483a105178b">Article 1: Mastering Java Threads</a></p><p><a href="https://medium.com/@VishathAmarasinghe/java-thread-lifecycle-1f50989ec454">Article 2: Java Thread Lifecycle</a></p><p>In a multithreading environment, have you ever experienced a situation where <strong>one thread updates a value, but another thread doesn’t see the change</strong>? Or maybe your program behaves unpredictably when multiple threads modify shared data?</p><p>This is where the <strong>Java Memory Model (JMM)</strong> comes in. The <strong>JMM defines the rules for how threads interact with memory</strong>, ensuring consistency and preventing hard-to-debug issues. In this article, we’ll break it down step by step with <strong>simple examples</strong>, so you can easily understand it!</p><h3>What is the Java Memory Model (JMM)?</h3><p>The <strong>JMM is a set of rules that define how Java handles memory in a multi-threaded environment.</strong> It ensures that threads communicate safely and reliably.</p><p>Here are the key rules of JMM:</p><ul><li><strong>Visibility:</strong> When one thread changes a value, that change should be visible to other threads.</li><li><strong>Ordering:</strong> Instructions should be executed in a predictable order to avoid unexpected behavior.</li><li><strong>Atomicity:</strong> Certain operations must be completed fully or not happen at all — there’s no in-between state.</li></ul><h3><strong>Real-World Analogy: The Coffee Shop</strong></h3><p>Imagine you walk into a <strong>busy coffee shop</strong> with multiple baristas making drinks. This coffee shop represents a <strong>multi-threaded environment</strong>, where different baristas (threads) work simultaneously.</p><p><strong>1️Visibility Issue (Stale Data)</strong></p><ul><li>You order a cappuccino, and the cashier (Thread 1) <strong>writes it on a sticky note</strong>.</li><li>The barista (Thread 2) <strong>doesn’t see the note immediately</strong> because it’s still on the cashier’s counter.</li><li>The barista starts making an espresso instead!<br> <strong>Solution:</strong> If the cashier immediately <strong>announces orders over a speaker</strong> (like using volatile), all baristas will hear the latest order.</li></ul><p><strong>2️ Reordering Issue (Instruction Order Change)</strong></p><ul><li>The barista first <strong>adds milk</strong> and then <strong>pours the coffee</strong> (correct order).</li><li>But if the instructions are mixed up and the coffee is poured before adding milk, the drink is ruined!<br> <strong>Solution:</strong> synchronized ensures <strong>steps happen in the correct order</strong>.</li></ul><p><strong>3️ Race Condition (Lost Updates)</strong></p><ul><li>Two baristas grab the same sticky note and <strong>both start making your cappuccino at the same time</strong>.</li><li>One finishes first, and the second barista <strong>throws away the drink</strong>, wasting effort.<br> <strong>Solution:</strong> synchronized prevents two baristas from working on the same order at the same time.</li></ul><p><strong>Takeaway</strong></p><p>Without JMM rules, a multi-threaded program behaves like <strong>a messy coffee shop</strong> where orders get mixed up. By applying visibility, ordering, and synchronization rules, we ensure the <strong>correct drinks (data) are served every time!</strong></p><p>So let’s see how we can implement this in the Java programming language</p><h3>Using volatile to Ensure Visibility</h3><p>volatile ensures that all threads always read the <strong>latest</strong> value from memory, preventing stale data issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*BUW12gUEwZutbzYxNq2r2w.png" /><figcaption>Example Code: Making variable volatile</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mJF5BfifLT3JCmiabN1dQ.png" /><figcaption>Main Method</figcaption></figure><h3>Using synchronized for Atomicity and Ordering</h3><p>Synchronized ensures that <strong>only one thread</strong> can execute a block of code at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7psCrDtz1CvXqPPL-Pa6qA.png" /><figcaption>making the method syncronized</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mW3PradJrxIgtahkRIrWVw.png" /><figcaption>Main method</figcaption></figure><h3>Using Thread.join() to Ensure Execution Order</h3><p>join() makes one thread <strong>wait</strong> for another to finish before continuing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BKWLhJqntmPtvHqYaQFCA.png" /><figcaption>Join usage</figcaption></figure><h3>Final Takeaways &amp; Best Practices</h3><p>Use volatile when you need <strong>visibility</strong> but no complex operations.<br>Use synchronized when you need <strong>atomicity and ordering</strong>.<br>Use join() when you need to <strong>ensure the execution order</strong>.</p><p>I think now you have the best understanding of the java memory Modal. use this in your code as a best practice to handle multithreading environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6eb86c6ff5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Thread Lifecycle]]></title>
            <link>https://medium.com/@VishathAmarasinghe/java-thread-lifecycle-1f50989ec454?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f50989ec454</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 03:33:54 GMT</pubDate>
            <atom:updated>2025-02-13T03:33:54.428Z</atom:updated>
            <content:encoded><![CDATA[<p>we discussed the basics of threads with real-world examples in our previous article. If you couldn’t be able to read it, try to go <a href="https://medium.com/@VishathAmarasinghe/mastering-java-threads-part-1-2483a105178b">read it</a>, today we will talk more deeply about the thread lifecycle and its states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8JbleeA1d1sQlm3PF8Z6Q.png" /></figure><p>In Java threads mainly it has <strong>six states</strong>.</p><p>To understand this let&#39;s take a thread as a woker in the factory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xPTcercqZX7PgrA7aKs6A.png" /><figcaption>Java Thread life Cycle</figcaption></figure><p>So now you have an understanding what are the lifecycle states of threads. Now let&#39;s go deeper and see how we can implement those in Java programming.</p><h3><strong>1. Creating and Starting a thread.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6piQUvrA7t7KWucpfa4LAw.png" /><figcaption>Creating and Starting a thread code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77QAkxxSloTk1EOVAVJUqQ.png" /></figure><h3><strong>2. Sleep() — pausing the work — timed waiting</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qtCQM8lp-BMl71n-jFiVw.png" /><figcaption>pausing the work — timed waiting Code</figcaption></figure><h3><strong>3. Yield() — letting another worker work first</strong></h3><p>Before moving to the coding with yield first let&#39;s see what is happening there in the foreground.</p><p>When a thread <strong>calls yield()</strong>, it <strong>pauses</strong> and lets <strong>other threads have a chance</strong> to run first.</p><p><strong>Real-World Example: Two Workers Sharing a Task</strong></p><p>Imagine two workers (<strong>Worker A</strong> and <strong>Worker B</strong>) are painting a wall together.</p><ul><li><strong>Worker A is painting</strong> but sees that <strong>Worker B can do it better</strong>.</li><li>Worker A says, <strong>“Hey, you go first! I’ll continue later.”</strong></li><li>So, Worker A <strong>steps aside</strong> and lets Worker B work.</li><li>Later, Worker A resumes work if there’s time.</li></ul><p>This is exactly what happens when a Java thread <strong>calls yield()</strong> — it <strong>suggests</strong> the CPU let another thread run first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNq6dMruv8zovXuTyDlqfw.png" /><figcaption>letting another worker work first Code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDpFew1S2UDaLK_QGoimwA.png" /></figure><h3><strong>4. Join() — waiting for another worker to finish the task.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JG5pMqQ4H2d1rzt6MiROA.png" /><figcaption>waiting for another worker to finish the task code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWexOB2e2a68__RIepEEdw.png" /></figure><h3><strong>5. Wait() and notify()</strong></h3><p>Before moving to the coding with wait() and notify() first let&#39;s see what is happening there in the foreground.</p><p><strong>Real-World Scenario: Worker Waiting for Supervisor’s Instructions</strong></p><p>Imagine a <strong>worker</strong> in a factory who <strong>cannot start working until</strong> the <strong>supervisor gives instructions</strong>.</p><ol><li>The worker <strong>sits and waits</strong> until the supervisor <strong>gives instructions</strong>.</li><li>The supervisor <strong>wakes up</strong> the worker when instructions are ready.</li><li>The worker <strong>starts working</strong> after getting instructions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mECz1oey44Res3Vf0jreqw.png" /><figcaption>Wait() and notify() code</figcaption></figure><h4>What Happens in This Code?</h4><p>1. The worker thread <strong>locks</strong> the station and calls wait().</p><ul><li>It prints: <strong>“Worker: Waiting for instructions…”</strong></li><li>The worker <strong>goes to sleep</strong> (it waits).</li></ul><p>2. The supervisor thread <strong>waits 2 seconds</strong> and then locks the station.</p><ul><li>It prints: <strong>“Supervisor: Giving instructions…”</strong></li><li>It calls notify() , which <strong>wakes up the worker</strong>.</li></ul><p>3. The worker thread <strong>resumes execution</strong> after being notified.</p><ul><li>It prints: <strong>“Worker: Got instructions, starting work!”</strong></li></ul><h3><strong>6. Interrupt() — Stopping the worker midway</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50AtIk3eoICyizJ6VD7DSw.png" /><figcaption>Interrupt() code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ahLIj3yy8wQfRzEtMfkSw.png" /></figure><p>Now I think you have a good understanding of the lifecycle of the java threads and how we can implement it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f50989ec454" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Java Threads — Part 1]]></title>
            <link>https://medium.com/@VishathAmarasinghe/mastering-java-threads-part-1-2483a105178b?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2483a105178b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 14:24:39 GMT</pubDate>
            <atom:updated>2025-02-05T14:24:39.323Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Mastering Java Threads — Part 1</strong></h3><p>I decided to write this article based on my experience from nearly eight months ago during my internship interview. One of the key technical questions I faced was about explaining the underlying mechanism of threads. Understanding Java threads is crucial for cracking coding interviews, especially when dealing with concurrency and multithreading concepts.</p><p>In this article, I’ll take you from the basics of threads to more in-depth details, helping you strengthen your knowledge and confidently tackle interview questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9m8VfdG2mp_JECzf3Vu8vg.png" /></figure><h3><strong>What Exactly is a Thread?</strong></h3><p>When you hear the word “thread,” what comes to mind? For a moment, forget about Java and just think about the word in a general context.</p><p>Do you have something in mind?</p><p>To understand threads in a relatable way, let’s consider a <strong>real-life scenario.</strong></p><p><strong>The Coffee Shop Analogy</strong></p><p>Imagine you walk into a coffee shop to order your favorite drink. A coffee shop operates like a computer program, and the staff inside are like threads — small workers performing different tasks simultaneously to ensure smooth operation.</p><p>Now, let’s see what happens if the coffee shop operates without multiple threads.</p><p><strong>Without Threads: One Worker Handling Everything</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*H_bjb-aCLVOHYerW1xgoDw.png" /><figcaption><strong>One Worker Handling Everything</strong></figcaption></figure><p>Suppose there’s only one worker in the entire coffee shop. This is how the process would go:</p><ol><li>They take your order.</li><li>They go to prepare the coffee.</li><li>They serve it to you.</li><li>Only then can they take the next customer’s order.</li></ol><p>Now, if a second customer walks in, they have to wait until the first order is fully completed before they can even place theirs. This makes the process <strong>slow and inefficient, leading to long wait times.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*GibKqYV5QBglcf9gjnra2A.png" /><figcaption>One Worker-multiple customers</figcaption></figure><p><strong>This is exactly how a program would function without threads. It executes one task at a time in a sequential manner, leading to performance bottlenecks.</strong></p><p>Now we’ll explore how introducing multiple threads (just like hiring more workers in a coffee shop) can significantly improve efficiency and make a system faster.</p><p><strong>With Threads: Multiple Workers Working Together</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*Yp1WcctLdb-T97h_w1NJ-g.png" /><figcaption><strong>Multiple Workers Working Together</strong></figcaption></figure><p>Now, imagine a more efficient system where multiple workers (threads) handle different tasks simultaneously:</p><ul><li>One worker takes orders.</li><li>Another worker prepares the coffee.</li><li>Someone else cleans the tables.</li><li>Another worker serves the drinks.</li></ul><p><strong>Now, the coffee shop runs smoothly because multiple tasks are happening at the same time — just like threads in a program!</strong></p><p><strong>Relating This to a Computer Program</strong></p><p>A computer without threads is like a coffee shop with only one worker — everything happens sequentially, leading to slow performance.</p><p>A computer <strong>with threads</strong>, on the other hand, allows multiple tasks to run at the same time. For example:</p><ul><li><strong>Playing music</strong> (One thread handles audio playback)</li><li><strong>Loading a website</strong> (Another thread fetches web content)</li><li><strong>Downloading a file</strong> (Yet another thread manages downloads)</li></ul><p>Each thread acts like a worker in a busy coffee shop, handling different tasks in parallel to improve efficiency.</p><p><strong>A Real-World Example: A Music App</strong></p><p>Think of a music streaming app:</p><ul><li>One thread is <strong>playing the current song</strong></li><li>Another thread is <strong>suggesting more songs</strong></li><li>A third thread is <strong>downloading the next track</strong></li></ul><p>Each of these tasks happens independently, ensuring a seamless user experience without interruptions.</p><p>Now that you have a solid understanding of what threads are, let’s dive deeper into key concepts related to Java threads in the next section!</p><h3>What is a Process?</h3><p>A <strong>process</strong> is like a large container that holds everything a program needs to run, including memory, CPU instructions, and resources.</p><p>For example, when you’re browsing the internet using <strong>Google Chrome</strong>, the <strong>entire browser acts as a process</strong>. Each <strong>tab</strong> you open, where you perform searches or stream videos, is similar to an individual <strong>thread</strong> running inside that process.</p><p>Threads within a process share the same memory and resources, making them efficient but requiring careful management.</p><h3>Threads and Resource Management</h3><p>Now that we understand the relationship between <strong>processes and threads</strong>, an important question arises:</p><p><strong>If multiple threads share resources inside a process, how do they manage those resources efficiently?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*d9CXAGLvFkb0Q52tJhXDCg.png" /><figcaption>Multiple Threads using resources and memory</figcaption></figure><p>Before diving into resource management, let’s first explore how we can create threads in Java.</p><h3>Creating Threads in Java</h3><p>Java provides <strong>two primary ways</strong> to create threads:</p><ol><li>Extending the <em>Thread class</em></li></ol><p>Key methods:</p><ul><li>run() → Defines the task the thread will execute.</li><li>start() → Starts the thread and tells Java to execute the run() method in a new thread.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7H811-hkNOm1X5PJ-sIgiw.png" /><figcaption>Extending the <em>Thread class-example</em></figcaption></figure><p>2. Implementing the <em>Runnable interface</em></p><p>This is a <strong>better approach</strong> because Java allows a class to extend only one other class, but a class can implement multiple interfaces.</p><p>The Runnable approach is preferred when you want your class to do other things besides just being a thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hO2rcfBFsXBo22dfJvY0Ew.png" /><figcaption>Implementing the <em>Runnable interface- Example</em></figcaption></figure><h3>Understanding Runnable vs. callable</h3><p>These two terms may sound similar, but they have key differences. Let’s simplify them with a real-life analogy.</p><p><em>Scenario 1: Runnable(Only do the job)</em></p><p>Imagine you run a <strong>pizza shop</strong>, and you have <strong>delivery workers (threads)</strong> to deliver pizzas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*YGHlUduhASQgfelwtaSwbA.png" /><figcaption>Runnable-example</figcaption></figure><p>You instruct a delivery worker:</p><ol><li>Pick up the pizza from the cashier.</li><li>Go to the delivery location.</li><li>Hand over the pizza.</li><li>Return to the pizza shop.</li></ol><p>The worker <strong>completes the task</strong> but doesn’t report back to you. They just <strong>do the job and return</strong>.</p><p>In Java, this is like Runnable → <strong>It performs a task but does not return any result.</strong></p><p><em>Scenario 2: Callable (Do it a</em>nd give me report back)</p><p>Now, imagine you want <strong>detailed feedback</strong> from your delivery worker.</p><p>You tell them: <strong>“Deliver the pizza and give me a report when you’re done.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*bv2r4nVwIKEEDfjVzMhFdQ.png" /><figcaption>Callable-example</figcaption></figure><p>So, after delivery, the worker returns with a report:<br> <em>“Pizza delivered successfully. It took 24 minutes.”</em></p><p>In Java, this is like Callable→ <strong>It performs a task and returns a result.</strong></p><p>I think now we all have enough understanding of these concepts. In the next article let&#39;s dive deeper into more complex theories with practices about Tread states and lifecycle. And thread synchronization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2483a105178b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is JavaBeans exactly?]]></title>
            <link>https://medium.com/@VishathAmarasinghe/what-is-javabeans-exactly-4ec0d8e4148e?source=rss-4ca0328b16f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec0d8e4148e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javabean]]></category>
            <dc:creator><![CDATA[Vishath Amarasinghe]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 11:02:43 GMT</pubDate>
            <atom:updated>2025-02-01T11:06:04.359Z</atom:updated>
            <content:encoded><![CDATA[<p>In software engineering interviews, especially for interns, associate software engineers, and even higher positions, candidates often get asked about JavaBeans. Many candidates get stuck because they find it tricky to explain the concept clearly. Based on my experience, I thought of writing an article that provides a simple, in-depth understanding of this important concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VOW99lsKDUSXDmrk1pZxA.png" /></figure><p>In any programming language, <strong>reusability</strong> is a key concern. To address this, Java introduced the concept of <strong>JavaBeans</strong>. A JavaBean is a software component designed to be reusable in different environments.</p><p>In simpler terms, a JavaBean is a special type of Java class used to <strong>store and manage data</strong> in an organized manner. Think of it as a <strong>container</strong> that holds information and provides a way to safely get and update that information.</p><p><strong>Key Characteristics of a JavaBean:</strong></p><ol><li><strong>Private fields</strong>: Data is stored securely and cannot be accessed directly.</li><li><strong>Public getter and setter methods</strong>: These methods control how the data is accessed and modified, providing a controlled way of interacting with it.</li><li><strong>No-argument constructor</strong>: This allows for easy creation of JavaBean objects without the need for complex initialization.</li><li><strong>Implements Serializable</strong>: This makes the JavaBean capable of being saved and transferred easily across different systems, ensuring the data can persist and be shared.</li></ol><p>By adhering to these rules, JavaBeans helps developers create classes that are organized, reusable, and efficient for managing data.</p><p>As an example let&#39;s take we have a POS application and it has a class to add product details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWTy-fPb_qGU_21UR-kXvQ.png" /></figure><p>Let&#39;s get a deeper understanding of JavaBeans with some simple real-world scenarios.</p><h3><strong>1. Has private fields.</strong></h3><p>Simply we call this data encapsulation which is one of the core OOP concepts.</p><p>Encapsulation — hiding the internal details of an object and only allowing controlled access to the data.</p><p><strong>Why this is a rule in JavaBeans?</strong></p><p>1. This keeps the data safe from accidental changes.</p><p>2 . Prevent direct access to the field.</p><p>Example: Imagine a bank system where the user’s balance should not be changed directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*UvcaZuMP8xUb0wm2AqHwAg.png" /><figcaption>Incorrect usage</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUC9wDhnWbGvNJGH_-VhVQ.png" /><figcaption>Incorrect usage</figcaption></figure><p>Corrected way</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*oTLanEWwgnM8SWKVR9YZMg.png" /></figure><p>With this method, we do not directly give the user to update the inner fields.</p><h3>2. Getter and setter methods(called this as controlled access)</h3><p>This 2nd rule has a relationship with the first rule. If we make a field private we cannot access it directly outside the class. Therefore we need to implement getters and setters to access these fields.</p><p>Ex: let&#39;s think we developed an e-commerce site. There we put the price for a product. So as our general knowledge, we know that price cannot be negative(- values)</p><p>So what we can do is by using getters and setters we can check the price is in the correct format. Which provides a safe way to access and update data. This allows validation before changing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1Lh0402llk6WEYagdsQzw.png" /></figure><h3>3. No argument constructors (make object creation easy)</h3><p>No argument constructor is a special type of constructor that does not take any parameters. It allows the creation of objects without passing any initial values.</p><p>Example: imagine we have a web app with the registration form.</p><p>A. At first, the form is empty.</p><p>B. The user enters their details.</p><p>C. The system saves the filled details later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5lUv9l7FdH0el1bK7h8nw.png" /></figure><p>No argument constructor is widely used in frameworks. Some tools like <strong>hibernate </strong>and <strong>spring</strong> automatically create objects and require a no-argument constructor.</p><p>Easy object creation: we can first create an object and then set values later.</p><p>Prevent errors: some frameworks break if a class only has parameterized constrictors.</p><p>Ex: in hibernate(JPA entity classes)</p><p>Hibernate uses reflection to create entity objects when fetching data from the database.</p><p>Why? Hibernate first creates an empty object, then fills in the data from the database.</p><h3>4. It is serializable</h3><p>When you first hear the word <strong>Serializable</strong>, it might sound a bit odd, but it’s actually a simple concept. <strong>Serializable</strong> means that an object can be turned into a format that can be saved, sent, or stored, and later restored back to its original form.</p><p>Think of it like a <strong>video game</strong>: Imagine you’re playing and you decide to <strong>pause</strong> the game. You can then <strong>close</strong> the game and come back later to <strong>reload</strong> the game exactly where you paused it. Serialization works in a similar way. It allows you to save the current state of an object and come back to it later.</p><p>We use <strong>Serializable</strong> when we need to:</p><ul><li>Save objects to files or databases.</li><li>Send objects over the network to other systems.</li><li>Transfer objects between different layers of an application, like in APIs.</li><li>Cache objects for faster retrieval.</li></ul><p>For example, in <strong>Hibernate</strong> and <strong>Spring Boot</strong>, we use Serialization to send objects through APIs or store them in databases. It helps make sure data can be safely saved, shared, and restored.</p><h3>Advantages of JavaBean</h3><ol><li>It is portable, Compact, and easy.</li></ol><p>JavaBeans follow a standard format, making them easy to use across different applications. (use desktop, mobile, and web without modifications)</p><p>2. The JavaBean properties and methods can be exposed to another application</p><p>It provides an easiness of reusing the software components.</p><p>Other applications can access JavaBean’s properties and methods using reflection and frameworks.</p><p>Ex: Spring Boot REST API can expose bean to frontend.</p><h3>Disadvantages of JavaBeans</h3><ol><li>JavaBeans are mutable. So it cannot take advantage of immutable objects.</li></ol><p>2. Creating a getter and setter method for each property separately may lead to the boilerplate code.</p><p>JavaBeans use getters and setters. Which means we can modify it after the object creation.</p><p>Immutable objects(objects that cannot be changed once created) are safer and better for concurrency.</p><p>So now we have an in-depth idea about what is exactly javaBeans what are the characteristics of that.</p><p><em>We can summarize it below</em></p><p><em>Since the 1 rule and 2 rules are in the OOP encapsulation concept we can combine them.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ka2QKKL2TJzXjKwusVaKg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec0d8e4148e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>