<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Code Baguette]]></title><description><![CDATA[Tech insights, Code snipsets]]></description><link>https://www.blog.dorceus.net/</link><image><url>https://www.blog.dorceus.net/favicon.png</url><title>Code Baguette</title><link>https://www.blog.dorceus.net/</link></image><generator>Ghost 5.47</generator><lastBuildDate>Fri, 04 Sep 2026 04:01:42 GMT</lastBuildDate><atom:link href="https://www.blog.dorceus.net/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Java atomic classes]]></title><description><![CDATA[<p>&#x2003;&#x2003;&#x2003;Java provides several built-in synchronization primitives to manage concurrent access to shared resources, including locks, semaphores, and atomic classes. Atomic classes are a unique type of synchronization primitive that allows for lightweight concurrent access to shared resources without the need for locks or semaphores. </p><p>In this article,</p>]]></description><link>https://www.blog.dorceus.net/java-atomic-classes/</link><guid isPermaLink="false">668282957a36897826c943d4</guid><dc:creator><![CDATA[Welinghton]]></dc:creator><pubDate>Thu, 11 Jul 2024 08:40:29 GMT</pubDate><media:content url="https://www.blog.dorceus.net/content/images/2024/07/atomium-brussels.jpg" medium="image"/><content:encoded><![CDATA[<img src="https://www.blog.dorceus.net/content/images/2024/07/atomium-brussels.jpg" alt="Java atomic classes"><p>&#x2003;&#x2003;&#x2003;Java provides several built-in synchronization primitives to manage concurrent access to shared resources, including locks, semaphores, and atomic classes. Atomic classes are a unique type of synchronization primitive that allows for lightweight concurrent access to shared resources without the need for locks or semaphores. </p><p>In this article, we will delve into the concept of atomic classes in Java, their<br>implementations, and best practices for using them effectively.</p><p>First thing first : What are Atomic Classes in Java?</p><p>&#x2003;&#x2003;Atomic classes are built-in synchronization primitives in Java that allow multiple threads to access a shared resource concurrently without the need for locks or semaphores. They provide a lightweight and efficient way to manage concurrent access to shared resources, making them ideal for high-contention scenarios. In this article we will not go into the pitfalls of multi-threading while using non-thread-safe variable. </p><p>Atomic classes can be used to implement a variety of synchronization primitives,<br>including</p><h2 id="atomic-variables">Atomic variables</h2><p>Atomic variables are simple variables that can be accessed by multiple threads simultaneously without the need for locks or semaphores.<br>They provide a convenient way to share data between threads without worrying about race conditions. Here is an example of how atomic<br>variables can be used:</p><figure class="kg-card kg-code-card"><pre><code class="language-java">public static class AtomicVariableExample {
            /**
     * Atomic variable to track how many time the operation has been * completed
     */
    private static final AtomicLong completed = new AtomicLong(0);
    private static Long nonThreadSafeVariable = 0L;

    public static void main(String[] args) throws InterruptedException{
        // Using Atomic Variable
        Runnable atomicTask = () -&gt; {
            completed.incrementAndGet();
            System.out.println(&quot;Incremented atomic variable &quot; + completed.get());
        };

        // Using synchronized block
        Runnable synchronizedTask = () -&gt; {
            synchronized (AtomicVariableExample.class) {
                nonThreadSafeVariable++;
                System.out.println(&quot;Incremented non thread safe variable &quot;+ nonThreadSafeVariable);
            }
        };
        var executor = Executors.newVirtualThreadPerTaskExecutor();
        for (var i = 0; i &lt; 10; i++) {
            executor.submit(atomicTask);
            executor.submit(synchronizedTask);
        }
        executor.awaitTermination(5, TimeUnit.SECONDS);
        
    }
    }</code></pre><figcaption>We have used an AtomicLong in this example but the other atomic classes behave about the same way.</figcaption></figure><h2 id="atomic-operations">Atomic operations</h2><p>Atomic operations are methods that perform a single operation on an atomic variable, such as incrementing or decrementing its value. These methods ensure that the operation is executed atomically, meaning that either the entire operation is completed, or it is rolled back and tried again if there is a failure. One might assume that incrementing or decrementing a variable is a single operation therefor there is no need for such complexity. However incrementing a variable <code>myVariable++</code> is actually two operations first you read the current value, then add one to it, and finally you assign that computed value to the variable <code>myVariable= myVariable + 1</code>. <br>Now that we got this out the way, here&apos;s &#xA0;an example of how atomic operations can be used:</p><h3 id="compare-and-swap">Compare And Swap</h3><pre><code class="language-java">package multithreading;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;

public class CompareAndSwapOperation {
    public static AtomicInteger atomicInteger = new AtomicInteger(0);
   
    public static void main(String[] args) throws InterruptedException {
        final var gen = new Random();
        final var executor = Executors.newVirtualThreadPerTaskExecutor();
        /**
         * CompareAndSwap (method named comparedAndSet)
         * this method compares the current value of the variable 
         * to an expected value, they are the same it set a new value and returns true
         * if the are not the same, it doesn&apos;t set the value and returns false
         */
        Runnable task = () -&gt; {
            var guessedValue = gen.nextInt(0, 10);
            var randomNewValue = gen.nextInt(0, 10);
            var correctGuess = atomicInteger.compareAndSet(guessedValue, randomNewValue);
            if (correctGuess) {
                System.out.println(&quot;We guess that the value was &quot; + guessedValue + &quot; and that was &quot; + correctGuess
                        + &quot; new value will be &quot; + randomNewValue);
            }
        };
        
        for (var i = 0; i &lt; 1000; i++) {
            executor.submit(task);
        }
        executor.awaitTermination(10, TimeUnit.SECONDS);
    }

}
</code></pre><p>There are many others atomic operations that we have not covered but I think this ones are the most important and the most used.</p><h2></h2><h2 id="best-practices">Best Practices</h2><ol><li>Use atomic classes sparingly:<br>Atomic classes should be used sparingly and only when necessary to avoid unnecessary overhead. They are best suited for situations where<br>a lightweight synchronization mechanism is required.</li><li>Use locks or semaphores in addition to atomic classes:<br>In some cases, you may want to use locks or semaphores in conjunction with atomic classes to provide an additional layer of<br>synchronization. This can help ensure that your code is both correct and efficient.</li><li>Test your code extensively:<br>Test your code thoroughly to ensure that it behaves correctly under different scenarios, including high-contention situations. This will<br>help identify any issues or bugs that may arise due to the use of atomic classes.</li></ol><h2 id="conclusion">Conclusion</h2><p>In conclusion, atomic classes are a powerful tool in Java for managing concurrent access to shared resources without the need for locks<br>or semaphores. By understanding their implementations and best practices, developers can create efficient and scalable multi-threaded<br>applications. Whether you&apos;re working on a simple web application or a complex enterprise system, mastering the art of atomic classes can<br>help you build robust and reliable software.</p>]]></content:encoded></item><item><title><![CDATA[Mastering Locks in Java: A Comprehensive Guide to Synchronization]]></title><description><![CDATA[<p></p><p>Multithreading is a fundamental aspect of modern software development, allowing developers to create applications that can handle<br>multiple tasks simultaneously. However, managing concurrent access to shared resources is crucial to avoid race conditions and other<br>synchronization issues. In Java, locks provide a simple way to synchronize access to shared resources,</p>]]></description><link>https://www.blog.dorceus.net/mastering-locks-in-java-a-comprehensive-guide-to-synchronization/</link><guid isPermaLink="false">6682800b7a36897826c943ca</guid><dc:creator><![CDATA[Welinghton]]></dc:creator><pubDate>Mon, 01 Jul 2024 10:09:05 GMT</pubDate><media:content url="https://www.blog.dorceus.net/content/images/2024/07/multi-threading.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.blog.dorceus.net/content/images/2024/07/multi-threading.png" alt="Mastering Locks in Java: A Comprehensive Guide to Synchronization"><p></p><p>Multithreading is a fundamental aspect of modern software development, allowing developers to create applications that can handle<br>multiple tasks simultaneously. However, managing concurrent access to shared resources is crucial to avoid race conditions and other<br>synchronization issues. In Java, locks provide a simple way to synchronize access to shared resources, ensuring that only one thread can<br>access the resource at a time. In this article, we will delve into the concept of locks in Java, their implementations, and best<br>practices for using them effectively.</p><p>What are Locks in Java?</p><p>A lock is a synchronization primitive that controls access to a shared resource. It ensures that only one thread can access the resource<br>at a time, preventing race conditions and deadlocks. In Java, locks are implemented using wait-and-signal semantics, where threads wait<br>for each other to release the lock before acquiring it themselves.</p><p>There are three built-in synchronization primitives in Java: ReentrantLock, ReentrantReadWriteLock, and Semaphore. Each of these locks<br>has its own strengths and weaknesses, which we will explore below:</p><ol><li>ReentrantLock:<br>ReentrantLock is the most commonly used lock implementation in Java. It provides a simple way to synchronize access to shared resources<br>by implementing the wait-and-signal semantics. The lock can be acquired and released by any thread, but only one thread can hold the lock<br>at a time. ReentrantLock provides two methods for synchronization:</li></ol><ul><li>acquire() : Acquires the lock, allowing the calling thread to access the shared resource.</li><li>release() : Releases the lock, allowing other threads to acquire it.</li></ul><p>Example Code:</p><pre><code class="language-java">public class MyThread extends Thread {
    private static ReentrantLock lock = new ReentrantLock();
    
    public void run() {
        System.out.println(&quot;Starting thread&quot;);
        try {
            lock.acquire(); // Acquires the lock
            // Critical section of code here
            System.out.println(&quot;Finished critical section&quot;);
            lock.release(); // Releases the lock
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code></pre><ol><li>ReentrantReadWriteLock:<br>ReentrantReadWriteLock is similar to ReentrantLock but provides read-write locks instead of just read or write locks. Read-write locks<br>allow multiple threads to read and write shared resources concurrently, making them useful for synchronizing access to large datasets.<br>The lock can be acquired and released by any thread, but only one thread can hold the lock at a time. ReentrantReadWriteLock provides two<br>methods for synchronization:</li></ol><ul><li>acquireRead() : Acquires the read lock, allowing the calling thread to read the shared resource.</li><li>acquireWrite() : Acquires the write lock, allowing the calling thread to modify the shared resource.</li></ul><p>Example Code:</p><pre><code class="language-java">public class MyThread extends Thread {
    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    
    public void run() {
        System.out.println(&quot;Starting thread&quot;);
        try {
            lock.acquireRead(); // Acquires the read lock
            // Reading shared resource here
            System.out.println(&quot;Finished reading shared resource&quot;);
            lock.releaseRead(); // Releases the read lock
            
            lock.acquireWrite(); // Acquires the write lock
            // Modifying shared resource here
            System.out.println(&quot;Finished modifying shared resource&quot;);
            lock.releaseWrite(); // Releases the write lock
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code></pre><ol><li>Semaphore:<br>Semaphore is a synchronization primitive that allows a set number of threads to access a shared resource concurrently. It provides a more<br>fine-grained control over concurrent access to shared resources compared to ReentrantLock and ReentrantReadWriteLock. Semaphore can be<br>acquired and released by any thread, but only a fixed number of threads can hold the lock at a time.</li></ol><p>Example Code:</p><pre><code class="language-java">public class MyThread extends Thread {
    private static Semaphore semaphore = new Semaphore(5); // Maximum 5 threads can access shared resource concurrently
    
    public void run() {
        System.out.println(&quot;Starting thread&quot;);
        try {
            semaphore.acquire(); // Acquires the lock
            // Accessing shared resource here
            System.out.println(&quot;Finished accessing shared resource&quot;);
            semaphore.release(); // Releases the lock
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code></pre><p>Best Practices:</p><ol><li>Avoid busy waiting:<br>Busy waiting occurs when a thread waits indefinitely for a lock to become available. Instead, use timeouts or other mechanisms to handle<br>cases where a thread is blocked waiting for a lock indefinitely.</li><li>Use timers for idle periods:<br>In situations where a thread is blocked waiting for a lock, it can use a timer to detect when a certain amount of time has passed. This<br>can help avoid wasting CPU cycles.</li><li>Consider using other synchronization primitives:<br>Depending on the complexity of your application, you may want to consider using other synchronization primitives such as queues or<br>messages, which can provide more fine-grained control over concurrent access to shared resources.</li><li>Use locks sparingly:<br>Locks should be used sparingly and only when necessary to avoid unnecessary delays and CPU usage.</li><li>Test your code thoroughly:<br>Test your code extensively to ensure that it behaves correctly under different scenarios, including high-contention situations.</li></ol><p>Conclusion:</p><p>In conclusion, locks are a crucial aspect of multithreading in Java. By understanding the different lock implementations available and<br>following best practices for their use, developers can create efficient and scalable concurrent applications. Whether you&apos;re working on a<br>simple web application or a complex enterprise system, mastering the art of synchronization can help you build robust and reliable<br>software.</p>]]></content:encoded></item><item><title><![CDATA[Console.log overdose]]></title><description><![CDATA[<p>Console.log is probably the most written line of code in the JavaScript language. Developers often use this function as a way to display values, assert value, create false breakpoints and so on. In this post we will explore some other functions that can help you write better code and</p>]]></description><link>https://www.blog.dorceus.net/console-log/</link><guid isPermaLink="false">668261268512f502bd32b601</guid><dc:creator><![CDATA[Welinghton]]></dc:creator><pubDate>Mon, 01 Jul 2024 08:50:56 GMT</pubDate><media:content url="https://www.blog.dorceus.net/content/images/2024/07/console-logs.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.blog.dorceus.net/content/images/2024/07/console-logs.png" alt="Console.log overdose"><p>Console.log is probably the most written line of code in the JavaScript language. Developers often use this function as a way to display values, assert value, create false breakpoints and so on. In this post we will explore some other functions that can help you write better code and avoid the &quot;console.log&quot; overdose.</p><p><strong>Console.assert</strong><br>Often what we want to achieve is to evaluate a condition in our code and print something int he console in case it fails. Assert takes a conditional expression and a string - it print the string if the expression evaluate to false.</p><figure class="kg-card kg-code-card"><pre><code class="language-js">if(!some_condition_that_should_always_be_true){
    console.log(&quot;Something is not right&quot;);
}

//Could be better written
console.assert(some_condition_that_should_always_be_true, &quot;Something is not right&quot;)</code></pre><figcaption>console.assert</figcaption></figure><p><strong>Console.count</strong><br>Some other time we just want to count how many time something happen during our code&apos;s execution. A cumbersome way of doing that is to print something with <code>console.log</code> each time the thing we want to track happen then filter our logs to manually count the occurrence. That approach has a lot of issues - the first being that you have to manually count the occurrence (in 2024, that&apos;s unthinkable); second you have to filter your logs which prevent you from looking at other log output while counting. The solution is <code>console.count</code> . &#xA0;</p><figure class="kg-card kg-code-card"><pre><code class="language-js">let a = 0

if(something_happended_to_a){
    a++;
    console.count(&quot;Inc A&quot;);
}
if(something_else_happend_to_a){
    a++;
    console.count(&quot;Inc A&quot;);
}
if(again_something_happend_to_a){
    a++;
    console.count(&quot;Inc A&quot;);
}</code></pre><figcaption>console.count</figcaption></figure><p><code>Console.count</code> returns the number of time it has been called with a particular label. In this snippet we have the label &quot;Inc A&quot; that has been used 3 times. </p><p><strong>Console.time</strong><br>Another common use case of <code>console.log</code> is to time calculate the execution time of a code block. Usually it is done by having a constant declared at the beginning of the block that holds the &#xA0;timestamp then declaring another constant that hold the timestamp at the end, then we can <code>console.log</code> the difference between the two timestamp. This is cumbersome and we are declaring boilerplate code into our code base. The solution is <code>console.time</code> and <code>console.timeEnd</code>.</p><pre><code class="language-js">//This is the block for which we want to calculate the execution time
console.time(&quot;myTimerLabel&quot;);
someComplexStuff();
moreComplexStuff();
console.timeEnd(&quot;myTimerLabel&quot;);</code></pre><p>Our timer start when we call <code>console.time</code> and ends when we call <code>console.timeEnd</code> in the console it prints the label that we used followed by the time that has passed between the two calls.</p>]]></content:encoded></item></channel></rss>