<?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 Devraj Singh on Medium]]></title>
        <description><![CDATA[Stories by Devraj Singh on Medium]]></description>
        <link>https://medium.com/@devrajcoder?source=rss-eddb28428c0e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gwa8OsfXh9uDHe5r7CT0dA.jpeg</url>
            <title>Stories by Devraj Singh on Medium</title>
            <link>https://medium.com/@devrajcoder?source=rss-eddb28428c0e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:42:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devrajcoder/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[How to design a thread safe class in Java.]]></title>
            <link>https://devrajcoder.medium.com/how-to-design-a-thread-safe-class-in-java-a51dd7987c5b?source=rss-eddb28428c0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a51dd7987c5b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Devraj Singh]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 16:23:06 GMT</pubDate>
            <atom:updated>2025-03-18T20:01:31.634Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Is a Thread-Safe Class?</h3><p>Wait, but what is a thread-safe class? A Java class is considered thread-safe when multiple threads can use it simultaneously without causing race condition or inconsistent states. Thread safety guarantee that even if multiple threads are accessing the same object of thread-safe class, the Java object will be in consistent state. If a Java class object will not be accessed by multiple threads, then there is no worry for thread-safety. You don’t need thread-safe class that in such scenario. I have seen many times in my project, theoretically Java class is not thread-safe, but they will not accessed by multiple thread at same time, hence the Java class doesn’t need to be thread-safe in that case.</p><h3>Understanding the Problem: Race Conditions</h3><p>Let’s look at a classic non-thread-safe class to understand why thread safety matters:</p><pre>public class UnsafeCounter {<br>    private int count = 0;<br>    <br>    public void increment() {<br>        count++; // This is not an atomic operation!<br>    }<br>    <br>    public void decrement() {<br>        count--; // This is not an atomic operation!<br>    }<br>    <br>    public int getCount() {<br>        return count;<br>    }<br>}</pre><p>Do you think increment and decrementmethod are thread-safe? No, because operations like count++ aren&#39;t atomic—they&#39;re actually three separate steps:</p><ol><li>Read the current value of count</li><li>Add/subtract 1</li><li>Write the new value back to count</li></ol><p>Here’s what can happen when two threads call increment() simultaneously when count is 0:</p><ul><li>Thread A reads count (0)</li><li>Thread B reads count (0)</li><li>Thread A adds 1 and writes 1</li><li>Thread B adds 1 and writes 1</li><li>The final result is 1 instead of the expected 2</li></ul><p>This is called a race condition, and it leaves our counter in an inconsistent state. The solution is to design the class a thread-safe.</p><h3>Strategies for Building Thread-Safe Classes</h3><h3>1. Stateless Classes: No State, No Problem</h3><p>If a class doesn’t maintain any state (fields), it’s automatically thread-safe. After all, if there’s nothing to modify, there’s nothing to corrupt!</p><pre>public class MathHelper {<br>    // No fields = no shared state<br>    <br>    public int add(int a, int b) {<br>        return a + b;<br>    }<br>    <br>    public static int multiply(int a, int b) {<br>        return a * b;<br>    }<br>    <br>    public double calculateAverage(int[] numbers) {<br>        int sum = 0;<br>        for (int num : numbers) {<br>            sum += num;<br>        }<br>        return numbers.length &gt; 0 ? (double) sum / numbers.length : 0;<br>    }<br>}</pre><p>This class is inherently thread-safe because each method operates only on its parameters, with no shared state between calls.</p><h3>2. Immutable Classes: Read-Only Is Your Friend</h3><p>Immutability is a powerful way to achieve thread safety. If an object can’t be modified after creation, there’s no risk of concurrent modifications.</p><pre>public final class ImmutablePoint {<br>    private final int x;<br>    private final int y;<br>    <br>    public ImmutablePoint(int x, int y) {<br>        this.x = x;<br>        this.y = y;<br>    }<br>    <br>    public int getX() { return x; }<br>    public int getY() { return y; }<br>    <br>    // Operations create new objects instead of modifying this one<br>    public ImmutablePoint translate(int dx, int dy) {<br>        return new ImmutablePoint(x + dx, y + dy);<br>    }<br>}</pre><p>The String class in Java is a perfect example of an immutable, thread-safe class. This is why you never have to worry about synchronization when using strings. <br>Use final whenever possible(that’s said by many wise Java experts), as it helps in unintentional modification and thread safety.</p><h3>3. Encapsulation and Synchronization</h3><p>For classes that need mutable state, proper encapsulation combined with synchronization is essential:</p><h4>Step 1: Make fields private</h4><p>Publicly accessible fields are a thread-safety violation:</p><pre>// Poor encapsulation - not thread-safe <br>public class UnsafeCounter { <br>   public int count; // Directly accessible, can be modified by any thread<br>}</pre><h4>Step 2: Identify non-atomic operations and synchronize them</h4><p>Once your fields are private, you need to ensure methods that modify state do so atomically:</p><pre>public class SafeCounter { <br>    private int count; // Hidden from external access <br>    <br>    public synchronized void increment() { <br>        count++; <br>    } <br>    <br>    public synchronized void decrement() {<br>        count--;<br>    }<br>    <br>    public synchronized int getCount() { <br>        return count; <br>    } <br>}</pre><p>The synchronized keyword ensures that only one thread can execute these methods on a particular instance at any given time. This prevents race conditions, but it does come with a performance cost due to locking overhead.</p><h4>The volatile keyword for visibility</h4><p>Sometimes, you don’t need full synchronization but do need to ensure that changes made by one thread are visible to other threads:</p><pre>public class StatusChecker {<br>    private volatile boolean running = true;<br>    <br>    public void stop() {<br>        running = false;<br>    }<br>    <br>    public void performTask() {<br>        while (running) {<br>            // Do something<br>        }<br>    }<br>}</pre><p>The volatile keyword ensures that changes to the variable are immediately visible to other threads, preventing visibility issues though it doesn&#39;t help with atomicity.</p><h4>Coarse-grained locking vs fine-grained locking</h4><p>Don’t be scared for the word coarse vs fine. Haha!. In simple word, Coarse-grained-locking means locking big area and fine-grained locking means locking small area.</p><p>Synchronizing entire method will work, but it has performance impact. It locks entire method and let’s say the method execution takes time, then many other thread will be waiting for long to enter inside the method.</p><p><strong>Coarse-grained locking</strong> means using fewer, broader locks that protect larger sections of code or data structures. Like locking an entire list when you only need to modify one element, or locking entire method where only a sub-portion of method needed to be synchronized.</p><p><strong>Fine-grained locking</strong> means using many smaller, targeted locks that protect specific components or operations. Like locking just the specific list element you’re modifying.</p><pre>// Coarse-grained locking<br>public synchronized void transferMoney(Account from, Account to, int amount) {<br>    from.debit(amount);<br>    to.credit(amount);<br>}</pre><pre>// Fine-grained locking<br>public void transferMoney(Account from, Account to, int amount) {<br>    synchronized(from) {<br>        synchronized(to) {<br>            from.debit(amount);<br>            to.credit(amount);<br>        }<br>    }<br>}</pre><p><strong>Key differences:</strong></p><ul><li><strong>Performance</strong>: Fine-grained typically allows higher concurrency and throughput as multiple threads can access different parts simultaneously. Coarse-grained can create bottlenecks.</li><li><strong>Complexity</strong>: Fine-grained is more complex to implement correctly and increases risk of deadlocks. Coarse-grained is simpler and safer to implement.</li><li><strong>Overhead</strong>: Fine-grained can have higher overhead from managing many locks. Coarse-grained has less lock management overhead but higher contention costs.</li></ul><p>The right approach depends on your specific application needs, balancing simplicity against performance requirements.</p><h3>4. Leveraging Thread-Safe Libraries</h3><p>To achieve fine-grained locking, Java provides many thread-safe collections and utilities that can simplify building thread-safe classes:</p><pre>import java.util.concurrent.ConcurrentHashMap;<br>import java.util.concurrent.atomic.AtomicInteger;</pre><pre>public class ThreadSafeUserManager {<br>    // Thread-safe map from java.util.concurrent<br>    private final ConcurrentHashMap&lt;String, User&gt; users = new ConcurrentHashMap&lt;&gt;();<br>    <br>    // Thread-safe counter using atomic classes<br>    private final AtomicInteger userCount = new AtomicInteger(0);<br>    <br>    public void addUser(String id, User user) {<br>        users.put(id, user);<br>        userCount.incrementAndGet();<br>    }<br>    <br>    public User getUser(String id) {<br>        return users.get(id);<br>    }<br>    <br>    public int getTotalUsers() {<br>        return userCount.get();<br>    }<br>}</pre><p>This approach uses fine-grained locking (internal to the concurrent collections) rather than coarse-grained locking (synchronizing entire methods), potentially improving performance under contention.</p><p>Common thread-safe components include:</p><ul><li><strong>Collections</strong>: ConcurrentHashMap, CopyOnWriteArrayList, ConcurrentLinkedQueue</li><li><strong>Atomic Variables</strong>: AtomicInteger, AtomicLong, AtomicReference</li><li><strong>Queues</strong>: LinkedBlockingQueue, ArrayBlockingQueue</li><li><strong>Synchronizers</strong>: CountDownLatch, CyclicBarrier, Semaphore</li></ul><h3>5. Thread Confinement: Each Thread Gets Its Own copy</h3><p>Sometimes, the best way to avoid sharing is not to share at all. Thread confinement means ensuring each thread has its own independent copy of data:</p><pre>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;</pre><p>ScopedValue (introduced in Java 21) is the modern replacement for ThreadLocal and offers better performance and cleaner semantics, especially with virtual threads.</p><pre>public class ScopedValueExample {<br>    // Define a ScopedValue (Java 21+)<br>    private static final ScopedValue&lt;String&gt; CURRENT_USER = ScopedValue.newInstance();<br>    public static void main(String[] args) {<br>        // Run code with a specific value bound to the ScopedValue<br>        ScopedValue.where(CURRENT_USER, &quot;Alice&quot;).run(() -&gt; {<br>            processRequest();<br>            <br>            // Value remains available in downstream methods<br>            auditAction(&quot;data_access&quot;);<br>        });<br>        // Multiple bindings in nested scopes<br>        ScopedValue.where(CURRENT_USER, &quot;Bob&quot;).run(() -&gt; {<br>            System.out.println(&quot;Outer scope: &quot; + CURRENT_USER.get());<br>            <br>            // Can rebind in an inner scope<br>            ScopedValue.where(CURRENT_USER, &quot;Charlie&quot;).run(() -&gt; {<br>                System.out.println(&quot;Inner scope: &quot; + CURRENT_USER.get());<br>            });<br>            <br>            // Outer binding is preserved<br>            System.out.println(&quot;Back to outer: &quot; + CURRENT_USER.get());<br>        });<br>    }<br>    private static void processRequest() {<br>        // Access the ScopedValue from another method<br>        System.out.println(&quot;Processing request for: &quot; + CURRENT_USER.get());<br>    }<br>    private static void auditAction(String action) {<br>        // Get user from ScopedValue without having to pass it as a parameter<br>        System.out.println(&quot;User &quot; + CURRENT_USER.get() + &quot; performed action: &quot; + action);<br>    }<br>}</pre><h3>6. Defensive Copying: Protect Your Internals</h3><p>When your class holds references to mutable objects, you should consider making defensive copies when accepting or returning those objects:</p><pre>public class DefensiveCalendar {<br>    private final Date startDate;<br>    <br>    public DefensiveCalendar(Date start) {<br>        // Defensive copy to prevent the caller from modifying our state<br>        this.startDate = new Date(start.getTime());<br>    }<br>    <br>    public Date getStartDate() {<br>        // Defensive copy to prevent the caller from modifying our state<br>        return new Date(startDate.getTime());<br>    }<br>}</pre><p>Without these defensive copies, a caller could modify the Date object even after passing it to your class, breaking encapsulation and potentially thread safety.</p><h3>Conclusion</h3><p>Building thread-safe classes in Java requires careful consideration of how your class will be used in concurrent environments. Let’s summarize our key strategies:</p><ol><li><strong>Stateless classes</strong> eliminate shared state entirely</li><li><strong>Immutable classes</strong> prevent modifications after construction</li><li><strong>Proper encapsulation</strong> with <strong>synchronization</strong> protects mutable state</li><li><strong>Thread-safe libraries</strong> provide building blocks for complex classes</li><li><strong>Thread confinement</strong> isolates state to individual threads</li><li><strong>Defensive copying</strong> protects against external modifications</li><li><strong>Lock granularity</strong> choices balance safety and performance.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RXZv6ICwn-nrmRgiSy5eA.png" /><figcaption>Visual guide for thread-safe class</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a51dd7987c5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java best practice: When to use Record over Class and vice-versa]]></title>
            <link>https://devrajcoder.medium.com/java-best-practice-record-over-class-and-vice-versa-c71902eb5d72?source=rss-eddb28428c0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c71902eb5d72</guid>
            <category><![CDATA[java-tips]]></category>
            <category><![CDATA[java-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-best-practices]]></category>
            <category><![CDATA[java-developer]]></category>
            <dc:creator><![CDATA[Devraj Singh]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 11:38:38 GMT</pubDate>
            <atom:updated>2023-07-17T19:29:04.709Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I got comments in my pull request to convert a given <em>Class</em> into <em>Record</em>. Then I pondered when we should be using <em>Record</em> instead of <em>Class</em> and when we should be using <em>Class</em> instead of <em>Record</em>. I dug more into this and wanted to pen down my thoughts.</p><p>Without further ado, let’s get started.</p><h4>What is a Record in Java?</h4><p>I’m assuming that you are fully aware of the <em>Record</em> in Java, but anyway, I will just briefly talk about it. The <em>Record</em> was first introduced in Java 14 as a preview and then became a standard feature in Java 16.</p><pre>// How to define a record<br>public record Person(String name, int age) { }</pre><pre>// How to use record.<br>Person person = new Person(&quot;Tommy&quot;, 21);<br>// getter methods of record.<br>System.out.println(person.name(), person.age());</pre><p>As the name suggests, <em>Record</em> is meant to hold an immutable record(i.e. some information). For example, I want to have a person&#39;s name and its DOB(date of birth), or country and its capital. These are immutable information. Earlier I would have created a POJO(Plain Old Java Object), or Hashmap. Obviously, those were not the cleanest solutions. For API Response, I often used to create Hashmap or POJO. Now I can just create a record:</p><pre>public record ApiResponse (int statusCode, String message) {}</pre><p><em>Record</em> has in-built <strong><em>toString()</em></strong>, <strong><em>equals()</em></strong> and <strong><em>hashCode()</em></strong></p><pre>Person tommy = new Person(&quot;Tommy&quot;, 12);<br>Person bomma = new Person(&quot;Bomma&quot;, 18);<br>Person bomma2 = new Person(&quot;Bomma&quot;, 18);<br><br>// in-built toString()<br>System.out.println(tommy);<br>// it will print: Person[name=Tommy, age=12]<br><br>// in-built equals()to check equality of two record<br>System.out.println(tommy.equals(bomma));// false<br>System.out.println(bomma2.equals(bomma));// true</pre><p>I won’t go into what are the advantage of <em>Record</em> over <em>Class</em> or vice-versa, because both have their own use case and we should be using them based on the situation.</p><h4>When we should be using Record over Class</h4><p>So let&#39;s talk about the main purpose of this article. When to use <em>Record</em>. The primary use case of the record is to hold immutable data. For examples: <em>point(x,y)</em>, <em>api-response(code, message),</em> <em>country(name, capital, continent)</em>, etc.</p><p>When a given class doesn’t have any setters method or any additional behavioral methods, then we can use Record. <strong>If a given <em>Class</em> has only the constructor and getters method, then it should be converted into Record.</strong></p><p>As stated above, <em>Record</em> are immutable. <strong>The fields are by-default final</strong>. Just like String, immutability in record helps in accidental modification in concurrent code and also helps in security.</p><p>We should be using <em>Record</em> whenever we can because it offers more concise and clear code. By default, it has <strong><em>toString()</em></strong>, <strong><em>equals(),</em></strong> and <strong><em>hashCode()</em></strong> and hence, improves readability by reducing the boilerplate code.</p><h4>When we should be using class over the record</h4><p>Most of the time we will be using class. When you have behavior, modifying the state of an instance, etc then you should be using class. For example, we have a <em>Person</em> class and methods like <em>updateAddress()</em>, <em>jump()</em>, <em>run()</em>, etc.</p><p>Apart from that, when you want to have customized <em>equals()</em>, <em>hashCode()</em>, or <em>toString()</em>, then you will have to use class, where you can write your own customized methods.</p><blockquote><strong>Rule of thumb</strong>: When you see class has only constructor and getter methods and no setter methods or any other behavioral methods, then you can refactor the Class into Record. When there is need of setters method, modifying the state of instance, or any behavioral methods, then obviously you will have to use class.</blockquote><p>If you have any additional thoughts or comments, please let me know in the comments section.</p><p><strong>So, did you find this article helpful?</strong> If you did, please consider buying me a coffee ;) <br><a href="https://www.buymeacoffee.com/devraj">https://www.buymeacoffee.com/devraj</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c71902eb5d72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing good and performant SQL queries]]></title>
            <link>https://devrajcoder.medium.com/writing-good-and-performant-sql-queries-bec2893d4d93?source=rss-eddb28428c0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bec2893d4d93</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Devraj Singh]]></dc:creator>
            <pubDate>Thu, 12 Aug 2021 13:13:02 GMT</pubDate>
            <atom:updated>2021-08-12T13:13:02.724Z</atom:updated>
            <content:encoded><![CDATA[<p>When the amount of data in the database is small, it doesn’t matter much (in terms of performance) how you write your SQL query and hence you will not notice any noticeable difference in the performance, but when there is significant data in the database, you will notice what is a slow query and what is fast and what is faster. Anyway, here are the few tips to write performant or faster or efficient (whatever you want to call) SQL queries.</p><p><strong>Never </strong><strong>SELECT *</strong> <br>It is really considered bad practice to use SELECT *. First SELECT * is slow. Many times, we don&#39;t need data from all columns. Fetching data for all columns makes it slow. Even if we need data for all columns, SELECT * is not considered a good practice. Using columns names in the SQL query makes it a cleaner query.</p><p><strong>Use </strong><strong>INNER JOIN rather than </strong><strong>WHERE<br></strong> I always used to join two tables using WHERE a clause(Bad habit). Using WHERE for joining two tables is bad in terms of performance. Here are the two ways to do inner join: <br>SELECT e.emp_no, s.salary FROM employee e, salary s WHERE e.emp_no=s.emp_no <br>and <br>SELECT employee.emp_no, salary.salary FROM employee INNER JOIN salary ON employee.emp_no=salary.emp_no <br>Now let&#39;s say the <em>employee</em> table has 40 rows and salary has 100 rows so in the case of FROM employee e, salary s WHERE , then in case one, it will create a cartesian product and will create 40*100=4000 results internally and then filter out based on WHERE condition.<br>While in the case of INNER JOIN, it will only create the rows which are matched</p><p><strong>Indexes<br></strong> The index in DB is a very powerful double-edged sword. Use it properly, it fastens your queries by many times. Use it in a bad way, it can hamper the performance. Here are a few things to remember while creating an index:<br><strong>a)</strong> Create indexes on columns that will be queried frequently. By default, many databases will create indexes on the primary key column and column with unique constraints. But you should not rely on that and create indexes manually. Hence, the column on which you are creating indexes should have UNIQUE constraints. Though it is not a hard rule, but a better approach.<br><strong>b)</strong> Prefer integer column than char column for creating indexes.<br><strong>c)</strong> Please please drop the unused indexes. Indexes are overhead and not worth if it is not used.<br><strong>d)</strong> Don’t create indexes on too many columns. It hampers the performance while doing insertion and deletion. So try to create indexes on the minimum number of columns.</p><p><strong>wildcard usage<br></strong> Consider below two SQL queries:</p><pre>SELECT name FROM employee WHERE name LIKE %john%; // not performant</pre><pre>SELECT name FROM employee WHERE name LIKE john%; // faster</pre><p>When you use the LIKE pattern <em>%john%</em>, then you should be aware of the performance penalty. You should avoid(if possible) a pattern that has a wildcard at the beginning of the pattern because in that case, the DBMS will do a full table scan of every row. On the other hand, <em>hello%</em> is always faster because it will only scan those columns whose column value starts with <em>hello</em>.</p><p><strong>WHERE is better than HAVING<br></strong>Use WHERE wherever possible and use HAVING when WHERE can’t serve the purpose.HAVING works on group functions while WHERE works on conditions based on the value of columns. Hence, HAVING will first bring all rows and then prepares the resultset while WHERE will first apply the condition and prepare the filtered result set. For example: <br>SELECT count(*),from_date FROM salaries WHERE from_date &gt; &#39;1980-11-24&#39; GROUP BY from_date; <br>is better than <br>SELECT count(*),from_date FROM salaries GROUP BY from_date HAVING from_date &gt; &#39;1960-11-24&#39;;</p><p><strong>Avoid sub-query<br></strong>sub-query is slow. inner subquery runs for every row for the table mentioned in the outer query. sub-query can mostly be replaced by JOIN operation. <br>SELECT emp_no FROM employees WHERE emp_no NOT IN (SELECT emp_no FROM salary); <br>can be replaced with <br>SELECT employee.emp_no FROM employees LEFT JOIN salaries WHERE salaries.emp_no IS NULL; <br>Another way to replace sub-query is to run sub-query separately and store the output in the variable which can be used by the main query later.</p><p><strong>Deleting all rows<br></strong>There are two ways to delete all rows in the table:</p><pre>TRUNCATE TABLE employees; -- faster<br>DELETE * FROM employees;</pre><p>Truncate is faster. Why? TRUNCATE is DDL and it will not maintain anything in the transaction logs. In the case of DELETE, it will delete each row at a time, write in the transaction logs and repeat the same for all rows. Hence slower. The downside of TRUNCATE is that it can’t be undone because it doesn’t write anything in the logs.</p><h3>Readability</h3><p>I follow this rule while writing SQL: First, make it work(return the correct result), then make it readable and then optimize it. <br>Write SQL keywords in capital letters so that they can be distinguished with table and column names.</p><pre>select name from employee; -- bad because SQL keywords are not CAPITALISED.</pre><pre>SELECT name FROM employees; -- good. Now I can easily spot the difference between SQL keyword and table and column name because SQL keyword are CAPITALISED.</pre><h3>Conclusion</h3><p>Having listed all the tips, please note that modern DBMS has an SQL optimizer and may optimize the query without your knowledge. However, it is always good to be aware of what is bad and good queries.</p><p><strong>References</strong></p><p><a href="https://docs.oracle.com/cd/B14117_01/appdev.101/b10795/adfns_in.htm">https://docs.oracle.com/cd/B14117_01/appdev.101/b10795/adfns_in.htm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bec2893d4d93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Go compiles so fast]]></title>
            <link>https://devrajcoder.medium.com/why-go-compiles-so-fast-772435b6bd86?source=rss-eddb28428c0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/772435b6bd86</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Devraj Singh]]></dc:creator>
            <pubDate>Sun, 31 Jan 2021 12:54:33 GMT</pubDate>
            <atom:updated>2022-08-10T02:42:43.464Z</atom:updated>
            <content:encoded><![CDATA[<p>Go is one of the fastest compiling programming languages out there. It compiles faster than most of the programming languages, like C/C++, Java, Rust, etc. Since the existing large codebase at Google used to take long hours to build, the quick compilation was one of the most important requirements during the creation of Golang at Google.</p><h4>Here are a few reasons why Golang compiles so fast:</h4><ol><li><strong>Eliminating cycles in Go dependencies graph</strong>: I believe this is one of the important reasons for Golang having a short compilation time. Cyclic dependency in Golang is a compilation error. So if you visualize the dependencies graph, there is no cycle in it. The entire dependency tree can be visualized as a directed acyclic graph. This makes the compilation process simple for Golang and it just has to compile recursively to the bottom of the dependencies tree. Since it is assumed that there will be no cyclic dependency, each Go package can be compiled independently and in parallel.</li><li><strong>Efficient Compiler Design keeping compilation speed in mind</strong>: Faster compilation was one of the most important design goals while creating Golang. Implementing a compiler is a complex thing and there are many design factors that affect the compilation time. Since faster compilation was one of the topmost priorities while designing Go, the Go team made every effort to create a very fast compiler. For example, it is mentioned in their official FAQ page: <em>Finally, it is intended to be fast: it should take at most a few seconds to build a large executable on a single computer. To meet these goals required addressing a number of linguistic issues: an expressive but lightweight type system; concurrency and garbage collection; rigid dependency specification; and so on. </em>(FAQ: <a href="https://golang.org/doc/faq">https://golang.org/doc/faq</a>)</li><li><strong>Go is very simple, lean, and minimalist</strong>: For example, there are only 25 keywords in Golang. Being simple and easy to learn was also one of the design choices while creating Golang. There are very little clutter and complexities. However, this also helped in faster compilation time.</li><li><strong>Efficient Dependency Analysis</strong>: Go will only include those packages which you have imported directly in the Go file. Unlike, C/C++ there are no headers here. C/C++ takes a lot of time just to parse the enormous amount of headers present in every C/C++ code.</li><li><strong>No symbol table</strong>: Symbol tables are slow. Language like C and C++ uses symbol table to parse the language. According to Go on its official website “<em>the language has been designed to be easy to analyze and can be parsed without a symbol table</em>”. No use of symbol table further increases the compilation speed.</li><li><strong>Eliminating unused dependencies</strong>: Unused import in Golang is an error. Any Go file can and will import the package it needs. While this may not be an important factor for faster compilation time, but it makes sure the compilation time is not increased due to unused packages.</li><li><strong>Few other reasons</strong>: In the book: “<strong><em>The Go Programming Language</em></strong>” written by <em>Brian Kernighan</em> and <em>Alan Donovan</em>, there are few reasons listed behind the faster compilation speed of Go: 1) All imports must be listed at the beginning of source file, so the compiler does not have to read the entire file to determine the dependencies. 2) Object file for a compiled Go package records export information not just for the package itself, but for its dependencies too. When compiling a package, the compiler must read one object file for each import but need not look beyond these files.</li></ol><h4>References:</h4><ul><li><a href="https://golang.org/doc/faq">Frequently Asked Questions (FAQ)</a></li><li><a href="https://stackoverflow.com/questions/2976630/how-does-go-compile-so-quickly">How does Go compile so quickly?</a></li></ul><p>If you have liked my articles, please support me here: <a href="https://www.buymeacoffee.com/devraj">https://www.buymeacoffee.com/devraj</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772435b6bd86" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>