<?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 Rupali Patel on Medium]]></title>
        <description><![CDATA[Stories by Rupali Patel on Medium]]></description>
        <link>https://medium.com/@rupalipatelkvc?source=rss-404af95ec299------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M3DEyru5AddUTyr887letA.jpeg</url>
            <title>Stories by Rupali Patel on Medium</title>
            <link>https://medium.com/@rupalipatelkvc?source=rss-404af95ec299------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:06:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rupalipatelkvc/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[GBDT Demystified: How LightGBM, XGBoost and CatBoost Work]]></title>
            <link>https://medium.com/@rupalipatelkvc/gbdt-demystified-how-lightgbm-xgboost-and-catboost-work-9479b7262644?source=rss-404af95ec299------2</link>
            <guid isPermaLink="false">https://medium.com/p/9479b7262644</guid>
            <category><![CDATA[boosting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[tabular-data]]></category>
            <category><![CDATA[catboost]]></category>
            <dc:creator><![CDATA[Rupali Patel]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 05:12:15 GMT</pubDate>
            <atom:updated>2025-01-22T05:12:15.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*LL3BE6BPMdjBm7R9WV_hGQ.png" /><figcaption>Gradient Boosting flow by ResearchGate</figcaption></figure><p>The Gradient Boosted Decision Tree is the state of the art model for tabular dataset. What makes the Gradient Boosting different than other models ? Let’s understand it.</p><p>In Gradient Boosting, subsequent predictors (another decision tree) are trained on the residual errors made by the previous tree.</p><p>GBDT calculate the loss or margin of error on every step, and in next step it calculates the difference of the remaining error. So at first, Suppose the ground truth is y, and predicted truth is y1 so the error or loss comes out to be (y — y1).</p><p>This becomes the ground truth for next decision tree. Now the new decision tree has predicted y2 as the truth, so the error or loss comes out to be ((y — y1) — y2). And the model continues. The final prediction becomes the sum of all the predicted truths at all the decision trees.</p><p>y^ = y1^ + y2^ + y3^ ….</p><p>In this blog, we will see one of the three implementations of GBDT along with tuning its hyperparameters to evaluate and understand the performance of these models on the dataset.</p><p>The three implementations are Catbost, XGBoost and Light GBM. Let’s dive into the CatBoost first.</p><h3>CatBoost GBDT :</h3><p>It is an open-source library developed by Yandex which can handle the dataset that contains both numerical and categorical features. To encode the categorical features, it uses Ordered Target Statistics.</p><p>Let’s try to understand in simple words what Ordered Target Statistics is.<br>To perform feature encoding, we have following methods to use — <br>1. One hot Encoding<br>2. Target Encoding<br>3. Label Encoding<br>4. Feature Hashing<br>5. Aggregating different labels into a single variable</p><p>With these methods, we convert categorical value into a numerical value based on the Target Statistics. For example -</p><p>When we have a categorical feature (like “color” with values “red,” “blue,” “green”), and we want to turn it into numbers, one clever way is to use the <strong>average target value</strong> for each category. For example:</p><ul><li>If “red” corresponds to an average target value of 0.8,</li><li>And “blue” corresponds to 0.3, We replace “red” with 0.8 and “blue” with 0.3.</li></ul><p>This is called <strong>Target Statistics</strong>. However, there’s a big problem called<strong> target leakage</strong>:</p><ul><li>The average target value for “red” is calculated using all the training data, which includes the target value (e.g., the label) for the very example we’re trying to predict. This can lead to artificially inflated performance, as the model “cheats” by looking at the answer.</li></ul><p>To solve this problem, Catboost do<strong> Ordered Target Statistics</strong>. As the name suggests, the values of Target Statistics for each example rely only on the observed history. This avoids the data leakage issue.</p><p>Also, let’s talk about the <strong>Tree Growing Strategy</strong> used by the CatBoost. It builds <strong>symmetric trees</strong>, meaning all leaves at a given level split on the same feature and threshold. It ensures faster training and inference as the structure is consistent.</p><p>I am adding a simple example through code which I ran in Colab to understand the working of the Catboost GBDT. I have used <a href="https://www.kaggle.com/datasets/pavansubhasht/ibm-hr-analytics-attrition-dataset">Employee attrition</a> dataset present on kaggle.</p><pre>!pip -qq install catboost</pre><p>After perfoming necessary exploratory data analysis and splitting the dataset into train and test (will write one blog detailing it), I arrive at the model building step.</p><pre>cboost = CatBoostClassifier(learning_rate = 1, depth = 1, scale_pos_weight = 6, l2_leaf_reg = 8, border_count = 65)<br>cboost.fit(x_df, y_df, cat_features = None)</pre><p>After building the model, I performed predictions on test data and evaluated the training and testing auc scores along with accuracy and F1.</p><blockquote><em>Note</em> : The value of the above hyperparams are decided with the help of <a href="https://hyperopt.github.io/hyperopt/">hyperopt</a>. Sharing one screenshot of output after tuning.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0GiuR_ESZuu9VL_-PKVBw.png" /><figcaption>hyperopt tuning hyperparams</figcaption></figure><p>With that, It’s a wrap up. I hope this blog gives you a basic intuition on CatBoost. The other two implementations will be part of next blog including benchmark results. Stay tuned.</p><h4>References:</h4><ul><li><a href="https://arxiv.org/abs/1706.09516">Arxiv Paper</a></li><li><a href="https://catboost.ai/en/docs/concepts/tutorials">Catboost Tutorial</a></li><li>Prof. Deepak Subramani’s Lecture at IISC</li></ul><p>I am a Graudate Student at UMD, College Park. I will be really happy if you show your support by liking the blog and sharing your thoughts in the comment section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9479b7262644" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tech Tales : The Mystery of the Multiple Emails (Part 2)]]></title>
            <link>https://medium.com/@rupalipatelkvc/tech-tales-the-mystery-of-the-multiple-emails-part-2-f8e9d8920e79?source=rss-404af95ec299------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8e9d8920e79</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[deadlock]]></category>
            <dc:creator><![CDATA[Rupali Patel]]></dc:creator>
            <pubDate>Sun, 01 Dec 2024 02:07:53 GMT</pubDate>
            <atom:updated>2024-12-01T02:07:53.328Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tech Tales : <em>The Mystery of the Multiple Emails (Part 2)</em></h3><blockquote>In my previous <a href="https://medium.com/@rupalipatelkvc/tech-tales-insights-from-everyday-engineering-fbb044a5a558">story</a>, I shared how users received multiple emails. This article is a follow-up that delves deeper into race condition and deadlock, how we can simulate them, and how to fix them with simple Java code. So grab a coffee — it’s going to be a long one.</blockquote><h3>What is a Race Condition?</h3><p>A <strong>race condition</strong> occurs when multiple threads access shared resources concurrently, and the final outcome depends on the timing of their execution. In other words, the behavior of the system is unpredictable and can vary depending on which thread wins the “race” to access the resource first. Race conditions often lead to subtle bugs that can be extremely hard to debug.</p><p><strong>Example of a Race Condition in Java : </strong>Consider a scenario where multiple threads are trying to increment a shared counter. If the increment operation is not synchronized, the threads can interfere with each other, resulting in an incorrect final value of the counter. Here is a simple Java code example that simulates the race condition:</p><pre>public class RaceConditionExample {<br>    private int counter = 0;<br><br>    public static void main(String[] args) {<br>        RaceConditionExample example = new RaceConditionExample();<br>        example.runTest();<br>    }<br><br>    public void runTest() {<br>        Thread t1 = new Thread(this::increment);<br>        Thread t2 = new Thread(this::increment);<br><br>        t1.start();<br>        t2.start();<br><br>        try {<br>            t1.join();<br>            t2.join();<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        System.out.println(&quot;Final Counter Value: &quot; + counter);<br>    }<br><br>    public void increment() {<br>        for (int i = 0; i &lt; 10000; i++) {<br>            counter++;  // This is not thread-safe, leading to a race condition<br>        }<br>    }<br>}</pre><p>Let’s run the above piece of code in our favorite IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-8-4KkmVUyC55N-l2Z7QA.png" /><figcaption>In the above code, two threads (t1 and t2) are incrementing the shared counter variable concurrently.</figcaption></figure><p>Since the incrementCounter() method is not synchronized, it leads to a race condition, and the final value of countermay not be 20000 as expected. Each thread could read the value of counter at the same time, increment it, and write it back, causing overwrites and missed increments.</p><h4>Fixing the Race Condition</h4><p>To fix the race condition, you need to synchronize access to the shared resource. You can do this using the synchronizedkeyword in Java:</p><pre>public synchronized void increment() {<br>        for (int i = 0; i &lt; 10000; i++) {<br>            counter++;  // This is not thread-safe, leading to a race condition<br>        }<br>}</pre><p>Let’s go back to IDE again to see the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ogC4q2BC9Kp6luw3kHMRWg.png" /><figcaption>With this change, only one thread can increment the counter at a time, ensuring that the final value of counter is correct.</figcaption></figure><p>That’s how we fix the race condition in Java. Now, Let’s dive into another topic.</p><h3>What is a Deadlock?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*-RjuuPY4IqZPnI8FoIk0ig.gif" /><figcaption>Deadlock (Sources : Wikipedia)</figcaption></figure><p>A <strong>deadlock</strong> occurs when two or more threads are waiting for each other to release resources, creating a circular dependency where none of the threads can proceed. This typically happens when multiple threads need multiple locks at the same time but acquire them in different orders.</p><p><strong>Example of a Deadlock in Java</strong> : Here’s a simple Java example that simulates a deadlock scenario.</p><pre>public class DeadlockExample {<br>    private final Object lock1 = new Object();<br>    private final Object lock2 = new Object();<br><br>    public static void main(String[] args) {<br>        DeadlockExample example = new DeadlockExample();<br>        example.runTest();<br>    }<br><br>    public void runTest() {<br>        Thread t1 = new Thread(this::task1);<br>        Thread t2 = new Thread(this::task2);<br><br>        t1.start();<br>        t2.start();<br>    }<br><br>    public void task1() {<br>        synchronized (lock1) {<br>            System.out.println(&quot;Thread 1: Holding lock 1...&quot;);<br>            try { Thread.sleep(100); } catch (InterruptedException e) {}<br><br>            System.out.println(&quot;Thread 1: Waiting for lock 2...&quot;);<br>            synchronized (lock2) {<br>                System.out.println(&quot;Thread 1: Acquired lock 2&quot;);<br>            }<br>        }<br>    }<br><br>    public void task2() {<br>        synchronized (lock2) {<br>            System.out.println(&quot;Thread 2: Holding lock 2...&quot;);<br>            try { Thread.sleep(100); } catch (InterruptedException e) {}<br><br>            System.out.println(&quot;Thread 2: Waiting for lock 1...&quot;);<br>            synchronized (lock1) {<br>                System.out.println(&quot;Thread 2: Acquired lock 1&quot;);<br>            }<br>        }<br>    }<br>}</pre><p>Let’s see what the above piece of code outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_lHrQ6GqVQXANdZ8kstgw.png" /><figcaption>Classic Deadlock Example — two threads waiting for each other.</figcaption></figure><h3>How to Avoid Deadlock</h3><p>A system falls into Deadlock when these four <em>Coffman conditions </em>occur:</p><ol><li><strong>Mutual Exclusion</strong>: Preventing mutual exclusion means that no process can have exclusive access to resources. Non-blocking synchronization algorithms help avoid mutual exclusion.</li><li><strong>Hold and Wait</strong>: To prevent holding and waiting for resources, processes can be required to request all needed resources at once or release all held resources before making new requests.</li><li><strong>No Preemption</strong>: Allowing preemption of resources can avoid deadlocks, but it’s often impractical due to the cost of rollback and potential inconsistency in processing outcomes. Lock-free, wait-free algorithms, and optimistic concurrency control are used to allow preemption.</li><li><strong>Circular Wait</strong>: Avoiding circular wait can be achieved by defining an order for resource requests or disabling interrupts during critical sections. Dijkstra’s solution and resource ordering are other methods used to avoid this condition.</li></ol><p>To avoid deadlock, we can follow certain strategies:</p><ul><li><strong>Lock Ordering</strong>: Always acquire locks in a particular order to avoid circular dependency.</li><li><strong>Timeouts</strong>: Use timeouts when trying to acquire locks, which helps in preventing threads from waiting indefinitely. I used this technique in case when <em>EmailService</em> failed in one environment.</li><li><strong>Deadlock Detection</strong>: Implement a mechanism to detect circular wait conditions and take corrective action such as <em>Process termination </em>and<em> Resource Preemption.</em></li></ul><p>Too much theory !! Let’s see what is there in Java to implement above mentioned strategies.</p><p><strong>ReentrantLock()</strong> : It provides mutual exclusion and has a <em>fairness</em> setting to ensure that waiting threads are granted access in order of their arrival time, reducing the risk of starvation.</p><pre>public class DeadlockExampleFixedTryLock {<br>    private final Lock lock1 = new ReentrantLock();<br>    private final Lock lock2 = new ReentrantLock();<br><br>    public static void main(String[] args) {<br>        DeadlockExampleFixedTryLock example = new DeadlockExampleFixedTryLock();<br>        example.runTest();<br>    }<br><br>    public void runTest() {<br>        Thread t1 = new Thread(this::task1);<br>        Thread t2 = new Thread(this::task2);<br><br>        t1.start();<br>        t2.start();<br>    }<br><br>    public void task1() {<br>        boolean lock1Acquired = false;<br>        boolean lock2Acquired = false;<br><br>        try {<br>            while (!lock1Acquired || !lock2Acquired) {<br>                lock1Acquired = lock1.tryLock();<br>                lock2Acquired = lock2.tryLock();<br><br>                if (lock1Acquired &amp;&amp; lock2Acquired) {<br>                    System.out.println(&quot;Thread 1: Acquired both locks&quot;);<br>                }<br>            }<br>        } finally {<br>            if (lock1Acquired) {<br>                lock1.unlock();<br>            }<br>            if (lock2Acquired) {<br>                lock2.unlock();<br>            }<br>        }<br>    }<br><br>    public void task2() {<br>        boolean lock1Acquired = false;<br>        boolean lock2Acquired = false;<br><br>        try {<br>            while (!lock1Acquired || !lock2Acquired) {<br>                lock1Acquired = lock1.tryLock();<br>                lock2Acquired = lock2.tryLock();<br><br>                if (lock1Acquired &amp;&amp; lock2Acquired) {<br>                    System.out.println(&quot;Thread 2: Acquired both locks&quot;);<br>                }<br>            }<br>        } finally {<br>            if (lock1Acquired) {<br>                lock1.unlock();<br>            }<br>            if (lock2Acquired) {<br>                lock2.unlock();<br>            }<br>        }<br>    }<br>}</pre><p>Let’s see its working in real time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*buP3FoFGg0yP9QztVb-qNA.png" /><figcaption>Working of ReentrantLock() method</figcaption></figure><p>And here is how to use <strong>timeout mechanism with Reentrant()</strong> :</p><pre>public class DeadlockExampleFixedWithTimeout {<br>    private final Lock lock1 = new ReentrantLock();<br>    private final Lock lock2 = new ReentrantLock();<br><br>    public static void main(String[] args) {<br>        DeadlockExampleFixedWithTimeout example = new DeadlockExampleFixedWithTimeout();<br>        example.runTest();<br>    }<br><br>    public void runTest() {<br>        Thread t1 = new Thread(this::task1);<br>        Thread t2 = new Thread(this::task2);<br><br>        t1.start();<br>        t2.start();<br>    }<br><br>    public void task1() {<br>        while (true) {<br>            boolean lock1Acquired = false;<br>            boolean lock2Acquired = false;<br><br>            try {<br>                lock1Acquired = lock1.tryLock(1, TimeUnit.SECONDS);<br>                if (lock1Acquired) {<br>                    System.out.println(&quot;Thread 1: Holding lock 1...&quot;);<br>                    Thread.sleep(50);<br><br>                    lock2Acquired = lock2.tryLock(1, TimeUnit.SECONDS);<br>                    if (lock2Acquired) {<br>                        System.out.println(&quot;Thread 1: Acquired lock 2&quot;);<br>                        // Perform the required task<br>                        break; // Successfully acquired both locks, exit loop<br>                    } else {<br>                        System.out.println(&quot;Thread 1: Could not acquire lock 2, releasing lock 1&quot;);<br>                    }<br>                } else {<br>                    System.out.println(&quot;Thread 1: Could not acquire lock 1&quot;);<br>                }<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            } finally {<br>                if (lock1Acquired) {<br>                    lock1.unlock();<br>                }<br>                if (lock2Acquired) {<br>                    lock2.unlock();<br>                }<br>            }<br>        }<br>    }<br><br>    public void task2() {<br>        while (true) {<br>            boolean lock1Acquired = false;<br>            boolean lock2Acquired = false;<br><br>            try {<br>                lock1Acquired = lock1.tryLock(1, TimeUnit.SECONDS); // allowing threads to attempt locking for a specified period<br>                if (lock1Acquired) {<br>                    System.out.println(&quot;Thread 2: Holding lock 1...&quot;);<br>                    Thread.sleep(50);<br><br>                    lock2Acquired = lock2.tryLock(1, TimeUnit.SECONDS);<br>                    if (lock2Acquired) {<br>                        System.out.println(&quot;Thread 2: Acquired lock 2&quot;);<br>                        // Perform the required task<br>                        break; // Successfully acquired both locks, exit loop<br>                    } else {<br>                        System.out.println(&quot;Thread 2: Could not acquire lock 2, releasing lock 1&quot;);<br>                    }<br>                } else {<br>                    System.out.println(&quot;Thread 2: Could not acquire lock 1&quot;);<br>                }<br>            } catch (InterruptedException e) {<br>                e.printStackTrace();<br>            } finally {<br>                if (lock1Acquired) {<br>                    lock1.unlock();<br>                }<br>                if (lock2Acquired) {<br>                    lock2.unlock();<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Let’s see the output on IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzVRbnoV7mWasiBgb963lA.png" /><figcaption>ReentrantLock() with timeout mechanism to avoid deadlock</figcaption></figure><p>This is the mechanism to avoid Deadlock in Java.</p><p>This definitely was a long read. But I hope I could explain the topics in simpler words. Do check out the complete code on <a href="https://github.com/rupalimits/tech-tales-java/tree/main/src/main/java/org/examples/deadlock">Github</a>.</p><p>For more details, see the following : <br>1. <a href="https://en.wikipedia.org/wiki/Deadlock_(computer_science)">Deadlock on Wikipedia</a><br>2. <a href="https://docs.oracle.com/cd/E17802_01/j2se/j2se/1.5.0/jcp/beta1/apidiffs/java/util/concurrent/locks/ReentrantLock.html">Reentrant() in official documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8e9d8920e79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tech Tales: Insights from Everyday Engineering]]></title>
            <link>https://medium.com/@rupalipatelkvc/tech-tales-insights-from-everyday-engineering-fbb044a5a558?source=rss-404af95ec299------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbb044a5a558</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[deadlock-avoidance]]></category>
            <dc:creator><![CDATA[Rupali Patel]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 02:35:45 GMT</pubDate>
            <atom:updated>2024-11-26T02:35:45.055Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The Mystery of the Multiple Emails: A Reactive Java Surprise</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dZFrn3rnj4k36syT" /><figcaption>Photo by <a href="https://unsplash.com/@kosherjellyfish?utm_source=medium&amp;utm_medium=referral">Jiayuan Lian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>During my work with asynchronous Java, specifically using Mono and Flux, I came across an unexpected behavior when triggering an email service. I noticed that the user was receiving the same email three times. After some investigation, I realized this was because we had three different environments — development, staging, and production — all of which were asynchronously updating the database. As a result, before the database check could confirm the state, the email was triggered multiple times from each environment, leading to multiple emails for the user (three in this case).</p><p><strong>The Solution: Implementing a Database Locking Mechanism</strong></p><p>To solve this problem, I implemented a Database Locking Mechanism that ensures that the email service triggers only once, regardless of the environment. This approach involves creating a lock system within the database to control when the email job is executed. Here is how I designed and implemented the solution:</p><p><strong>Step 1: Creating a Lock Table</strong></p><p>The first step was to create a table named job_lock that would keep track of which jobs are currently locked. This table helps ensure that only one instance can proceed with a job at a given time.</p><p>The table was created as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJ3_uU_IcPGx5GO50_orww.png" /><figcaption>Command to create job_lock table in SQL</figcaption></figure><ul><li><strong>job_name</strong>: This field uniquely identifies the job that is being executed. It ensures that the same job cannot be executed by multiple instances at the same time.</li><li><strong>locked</strong>: This boolean field indicates whether the job is currently locked (i.e., being processed).</li></ul><p><strong>Step 2: Implementing the JobLockService</strong></p><p>The core of the solution is the JobLockService class, which is responsible for managing the locking mechanism. The service uses methods to acquire, release, and handle rollbacks of locks, leveraging reactive programming principles to handle asynchronous execution.</p><p><strong>Method 1: </strong><strong>acquireLock(String jobName)<br></strong>This method is used to acquire a lock for a specific job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j251pHcKsUZACTdn3KU2yA.png" /><figcaption>acquireLock(String JobName) -&gt; Method which acquire lock for a job and create an entry in the job_lock table</figcaption></figure><ul><li><strong>Acquire Connection</strong>: A connection is created from the connectionFactory.</li><li><strong>Begin Transaction</strong>: The connection begins a transaction to ensure that all subsequent operations are performed atomically.</li><li><strong>Lock Acquisition (SELECT FOR UPDATE)</strong>: The SELECT * FROM job_lock WHERE job_name = $1 FOR UPDATE statement is executed to attempt to acquire a lock. The FOR UPDATE clause ensures that only one instance can select and lock the row for a given job, thus preventing race conditions.</li><li><strong>Insert New Lock Record</strong>: If no existing lock record is found, a new lock record is inserted (INSERT INTO job_lock) with the job name and a locked status of true.</li><li><strong>Release Connection</strong>: The connection is closed after the operation.</li></ul><p><strong>Method 2: </strong><strong>releaseLock(String jobName)<br></strong>This method releases a lock once the job is completed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zAGqMl3LmKrxxz8GJigOw.png" /><figcaption>releaseLock(String jobName) -&gt; Method which releases lock and deleted entry from the job_lock table when email trigger is done</figcaption></figure><ul><li><strong>Acquire Connection</strong>: A connection is created from the connectionFactory.</li><li><strong>Begin Transaction</strong>: The connection begins a transaction to ensure atomicity.</li><li><strong>Delete Lock Record</strong>: The lock record for the given job name is deleted from the job_lock table.</li><li><strong>Commit Transaction</strong>: The transaction is committed, ensuring that the lock release is finalized.</li><li><strong>Release Connection</strong>: The connection is closed after the operation.</li></ul><p><strong>Method 3: </strong><strong>releaseLockAndRollback(String jobName)<br></strong>This method is used to release a lock and roll back a transaction in case of errors during job execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5kPC63ozCqZEuxDMmGpmA.png" /><figcaption>releaseLockAndRollback(String jobName) -&gt; Method which rolls back in case of error during email triggering</figcaption></figure><ul><li><strong>Acquire Connection</strong>: A connection is created from the connectionFactory.</li><li><strong>Rollback Transaction</strong>: The transaction is rolled back, undoing any changes that may have been made during the failed job execution.</li><li><strong>Delete Lock Record</strong>: The lock record for the given job name is deleted to ensure that other instances can proceed with the job.</li><li><strong>Release Connection</strong>: The connection is closed after the operation.</li></ul><h4>Key Features of This Approach -</h4><ol><li><strong>Database Locking</strong>: When an instance attempts to acquire the lock, it executes a SELECT FOR UPDATE statement on the job_lock table. This locks the selected row, ensuring that only one instance can acquire the lock at a time, thus avoiding race conditions.</li><li><strong>Unique Constraint</strong>: The job_lock table has a unique constraint on the job_name field. This prevents multiple instances from acquiring a lock for the same job. If another instance attempts to insert a lock record while the lock is already held, the database raises a unique constraint violation error, ensuring safety.</li><li><strong>Deadlock Scenario Solution</strong>: In case of errors or deadlocks, the releaseLockAndRollback method ensures that the lock is released and the transaction is rolled back. This prevents deadlocks and ensures that the system remains consistent.</li></ol><blockquote>By implementing this Database Locking Mechanism using reactive programming, I was able to solve the issue of the email being sent three times across different environments. The locking mechanism ensured that only one instance could trigger the email service at any given time, preventing duplicate emails. This solution also provided safeguards against race conditions and ensured proper handling of deadlocks, making the system more robust and reliable.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbb044a5a558" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>