<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Code Craft Club</title>
    <description>The latest articles on DEV Community by Code Craft Club (@codecraftclub).</description>
    <link>https://dev.to/codecraftclub</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1156672%2F484f6b51-483c-4721-9159-c422f4eec7f7.png</url>
      <title>DEV Community: Code Craft Club</title>
      <link>https://dev.to/codecraftclub</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/codecraftclub"/>
    <language>en</language>
    <item>
      <title>COMPARATOR vs COMPARABLE - A Java Surprise You did in School!</title>
      <dc:creator>Code Craft Club</dc:creator>
      <pubDate>Sat, 16 Mar 2024 17:19:38 +0000</pubDate>
      <link>https://dev.to/codecraftclub/comparator-vs-comparable-a-java-surprise-you-did-in-school-289e</link>
      <guid>https://dev.to/codecraftclub/comparator-vs-comparable-a-java-surprise-you-did-in-school-289e</guid>
      <description>&lt;p&gt;Ever felt like &lt;code&gt;Comparable&lt;/code&gt; and &lt;code&gt;Comparator&lt;/code&gt; were taunting you in Java? You're not wrong! These two interfaces can be a bit mysterious at first, even after conquering mountains of tutorials. (Don't worry, I wrestled with them too!) After enough head-scratching and questionable Google searches (Documentation is great, but sometimes you just need a friendly explanation to break things down, FWIW), I finally cracked the code on these confusing critters.&lt;/p&gt;

&lt;p&gt;So forget complex explanations and cryptic code! In this blog, we'll break down &lt;code&gt;Comparable&lt;/code&gt; and &lt;code&gt;Comparator&lt;/code&gt; with a &lt;strong&gt;down-to-earth analogy&lt;/strong&gt; that'll surely seep into your logical minds. Trust Me!&lt;/p&gt;

&lt;p&gt;Plus, we'll walk you through a &lt;strong&gt;simple 3-step process&lt;/strong&gt; for implementing each one!&lt;/p&gt;

&lt;p&gt;So Let's Begin!&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's head back to Schooling Days
&lt;/h2&gt;

&lt;p&gt;Ever wonder why students seem to magically line up by &lt;strong&gt;HEIGHT&lt;/strong&gt; during school assemblies? It's like they have a built-in sorting algorithm! I am sure you must've also done this!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyitokscu3jo2d7qv5o0i.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyitokscu3jo2d7qv5o0i.jpeg" alt="Height" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Well, that's kind of what &lt;code&gt;Comparable&lt;/code&gt; does in Java. It lets objects define their own natural ordering, just like those height-conscious students. No external instructions needed - they just know their place!&lt;/p&gt;

&lt;p&gt;Sound's as simple as that… But let's take a closer look at this to understand better!&lt;/p&gt;




&lt;h2&gt;
  
  
  Comparable: A Natural Order of Students
&lt;/h2&gt;

&lt;p&gt;Comparable is like a default instruction given to the students on how to line up naturally without any additional directions.&lt;/p&gt;

&lt;p&gt;So Let's take a Student class just like a real time student in a school.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Student {
    String name;
    int height;
    int weight;

    public Student(String name, int height, int weight) {
        this.name = name;
        this.height = height;
        this.weight = weight;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Just like how a student knows naturally to compare as per height with his companions, the same capability can be given to our Student Class in java using the Comparable interface.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz8tgj5ta325ycd297ozi.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz8tgj5ta325ycd297ozi.jpeg" alt="Height Check" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So let's implement the Comparable interface and let's make it happen in just 3 steps as below.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementation of Comparable Interface in 3 Steps:
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Implement the Comparable Interface:
&lt;/h3&gt;

&lt;p&gt;To make a class sortable using the natural order, you implement the &lt;code&gt;Comparable&lt;/code&gt; interface directly in the class.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Keep in mind! Comparable interface grants the class the natural ability to compare itself whenever necessary."&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Student implements Comparable&amp;lt;Student&amp;gt; {
 ....
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Override the compareTo() Method:
&lt;/h3&gt;

&lt;p&gt;Just override the &lt;code&gt;compareTo()&lt;/code&gt; method inside your class. This method compares the current object (&lt;code&gt;this&lt;/code&gt;) with another object of the same type (&lt;code&gt;other&lt;/code&gt;).&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Think of it as the class's superpower, allowing it to compare naturally whenever the need arises.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Student implements Comparable&amp;lt;Student&amp;gt; {
    String name;
    int height;
    int weight;

    public Student(String name, int height, int weight) {
        this.name = name;
        this.height = height;
        this.weight = weight;
    }

    @Override
    public int compareTo(Student other) {
        // Compare students based on their height
        return this.height - other.height;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;If the current &lt;strong&gt;object should come before the other object, return a negative integer&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;If they are &lt;strong&gt;equal, return 0&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;If the current &lt;strong&gt;object should come after the other object, return a positive integer&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3. Using Comparable:
&lt;/h3&gt;

&lt;p&gt;Once Comparable is implemented, Java's built-in sorting methods will use the natural order defined by the &lt;code&gt;compareTo()&lt;/code&gt; method.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Yipee! The magic now happens naturally. The objects get sorted naturally now!&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Arrays.sort(students);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Now let's see a twist in our example..
&lt;/h2&gt;

&lt;p&gt;Imagine if the students were suddenly tasked with lining up by their &lt;strong&gt;WEIGHT&lt;/strong&gt; instead of their height! This is something not natural to the students and is a custom defined instruction given to them. &lt;/p&gt;

&lt;p&gt;Just like the teacher guiding the students to line up by weight, the &lt;code&gt;Comparator&lt;/code&gt; interface in java too provides an external logic to sort objects based on specific criteria.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuu7csps89u6gh0g3jcuf.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuu7csps89u6gh0g3jcuf.jpeg" alt="WEIGHT CHECK" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So let's implement the &lt;code&gt;Comparator&lt;/code&gt; interface and let's make it happen in just 3 steps again.&lt;/p&gt;

&lt;h2&gt;
  
  
  Implementation of Comparator Interface in 3 Steps:
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Create a Comparator Class:
&lt;/h3&gt;

&lt;p&gt;To implement a &lt;code&gt;Comparator&lt;/code&gt;, you need to create a separate class that implements the Comparator interface. This interface requires you to define the &lt;code&gt;compare()&lt;/code&gt; method.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Keep in mind simple that - Comparator is just a external Instructor! As simple as a teacher at school in our case!&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.Comparator;

public class WeightComparator implements Comparator&amp;lt;Student&amp;gt; {
    ....
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Override the compare() Method: 
&lt;/h3&gt;

&lt;p&gt;Inside the &lt;code&gt;Comparator&lt;/code&gt; class, you override the &lt;code&gt;compare()&lt;/code&gt; method. This method takes two objects of the type you're comparing (in this case, Student objects) and returns an integer value based on their comparison.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Just as a teacher compares one student's weight after another to sort, think of this method as the Java equivalent. It's like having your own personal sorting instructor built right into your code!&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.Comparator;

public class WeightComparator implements Comparator&amp;lt;Student&amp;gt; {
    @Override
    public int compare(Student s1, Student s2) {
        // Compare students based on their weight
        return s1.weight - s2.weight;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;If the current object should come before the other object, return a negative integer.&lt;/li&gt;
&lt;li&gt;If they are equal, return 0.&lt;/li&gt;
&lt;li&gt;If the current object should come after the other object, return a positive integer.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3. Use the Comparator:
&lt;/h3&gt;

&lt;p&gt;Once your &lt;code&gt;Comparator&lt;/code&gt; is defined, you can use it to sort objects in various ways. For example, you can use it with the &lt;code&gt;Arrays.sort()&lt;/code&gt; method or with collections like &lt;code&gt;ArrayList&lt;/code&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Now, you're putting the teacher to work in your Java program by calling the sort method along with the comparator.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Arrays.sort(students, new WeightComparator());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;em&gt;Get your coding hands on your keyboards and give this a try! I'm confident it will streamline your programming experience. Remember, don't hesitate to reach out for additional help and suggestions.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Closing Thoughts:
&lt;/h2&gt;

&lt;p&gt;Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you'd like us to break open and cook it simpler in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.&lt;/p&gt;

&lt;p&gt;Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>java</category>
      <category>sorting</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Streams in Java made super simple with examples! — An Easy Beginner’s Guide!</title>
      <dc:creator>Code Craft Club</dc:creator>
      <pubDate>Sun, 01 Oct 2023 19:17:16 +0000</pubDate>
      <link>https://dev.to/codecraftclub/streams-in-java-made-super-simple-with-examples-an-easy-beginners-guide-pcj</link>
      <guid>https://dev.to/codecraftclub/streams-in-java-made-super-simple-with-examples-an-easy-beginners-guide-pcj</guid>
      <description>&lt;p&gt;Data structures such as arrays, sets, etc. are commonly used to store and manipulate data in Java. However, iterating over these data structures and performing operations on them can be cumbersome. Java 8 introduced a new feature called Streams, which allows us to process data in a declarative and functional way making it more safer and concise.&lt;/p&gt;

&lt;p&gt;In this blog, we will discuss about the concept and working of Streams in Java with a delightful analogy that makes it super easy!&lt;/p&gt;

&lt;h2&gt;
  
  
  Stream
&lt;/h2&gt;

&lt;p&gt;A stream is a way of processing a sequence of elements in a functional and declarative manner. &lt;strong&gt;A stream does not store the data itself, but only provides a view of the data source&lt;/strong&gt;. This means that the data source is not modified by the stream operations.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Imagine Java Streams like a stream of vehicles passing through a toll gate. Each vehicle represents an element in the stream. Just as vehicles pass through a toll gate one by one, elements in a stream are processed sequentially or in parallel.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3kvd2ayzxrwhmtuj0wnw.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3kvd2ayzxrwhmtuj0wnw.jpeg" alt="toll"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Java provides a Stream interface in the &lt;code&gt;java.util.stream&lt;/code&gt; package that defines the methods for creating and manipulating streams. &lt;/p&gt;

&lt;p&gt;However, the Stream interface does not support &lt;code&gt;primitive&lt;/code&gt; types such as &lt;code&gt;int&lt;/code&gt;, &lt;code&gt;long&lt;/code&gt;, and &lt;code&gt;double&lt;/code&gt;. To use streams with these types, we need to use their corresponding wrapper classes &lt;code&gt;Integer&lt;/code&gt;, &lt;code&gt;Long&lt;/code&gt;, and &lt;code&gt;Double&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating an Empty Stream
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;Stream&lt;/code&gt; interface consists of a &lt;code&gt;static&lt;/code&gt; and default method &lt;code&gt;empty()&lt;/code&gt; that can be used to create an empty stream.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Creating an empty stream in Java is similar to having an empty toll lane at a toll gate. Just as an empty lane at a toll gate waits for vehicles to pass through, an empty stream in Java is ready to receive elements for processing. It serves as a placeholder, waiting to be filled with data before any operations can be performed on it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd6nj8i66jlp322xpat1j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd6nj8i66jlp322xpat1j.png" alt="empty stream"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above code, we have created an empty stream using the default method &lt;code&gt;empty()&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Creating a Stream with Collections&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;In Java, we can create a &lt;code&gt;Stream&lt;/code&gt; from a collection (such as a List, Set, or Map) using the &lt;strong&gt;&lt;code&gt;stream()&lt;/code&gt;&lt;/strong&gt; method. Here’s how we can create a Stream from various types of collections:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Syntax:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="n"&gt;collection&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;stream&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example Syntax -&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9jz2bkb6mov5k407s690.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9jz2bkb6mov5k407s690.png" alt="stream collec"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above code, we have created a list of &lt;code&gt;Strings&lt;/code&gt; and assigned it to &lt;code&gt;myList&lt;/code&gt; variable. From the list of &lt;code&gt;Strings&lt;/code&gt; we have created a stream and assigned it to the &lt;code&gt;streamFromList&lt;/code&gt;. Here, the stream does not occupy any memory, instead it just provides a way to access the original elements.&lt;/p&gt;

&lt;h3&gt;
  
  
  Direct creation of Stream
&lt;/h3&gt;

&lt;p&gt;In Java, the &lt;strong&gt;&lt;code&gt;Stream.of()&lt;/code&gt;&lt;/strong&gt; method is a convenient way to create a Stream from a sequence of elements. It allows us to create a Stream directly from individual elements or an array of elements without needing a collection.&lt;/p&gt;

&lt;p&gt;Here’s how you can use the &lt;strong&gt;&lt;code&gt;Stream.of()&lt;/code&gt;&lt;/strong&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Stream&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;of&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;list&lt;/span&gt; &lt;span class="n"&gt;of&lt;/span&gt; &lt;span class="n"&gt;elements&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example Syntax -&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcweusbjcwgobukfae1o0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcweusbjcwgobukfae1o0.png" alt="Streamof"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to work with Streams?
&lt;/h2&gt;

&lt;p&gt;Working with Streams involves the usage of some operations. These operations are basically divided as &lt;strong&gt;Intermediate Operations&lt;/strong&gt; and &lt;strong&gt;Terminal Operations&lt;/strong&gt;. Let us understand these terms easily using the same analogy of a Toll Booth.&lt;/p&gt;

&lt;h2&gt;
  
  
  Intermediate Operations
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Intermediate operations are like toll booth workers who filter, transform, or manipulate the vehicles before they leave the toll gate. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;These intermediate operations &lt;strong&gt;always produces a new &lt;code&gt;stream&lt;/code&gt; as output&lt;/strong&gt; after performing the specified operations.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffvorq74ofph5qnqp90dn.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffvorq74ofph5qnqp90dn.jpeg" alt="toll2"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There are different types of intermediate operations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;filter()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;map()&lt;/code&gt; &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sorted()&lt;/code&gt; &lt;/li&gt;
&lt;li&gt;
&lt;code&gt;distinct()&lt;/code&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Filter()
&lt;/h3&gt;

&lt;p&gt;Filtering allows us to select elements based on a certain condition.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqfyss7f2r54ggbag8toz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqfyss7f2r54ggbag8toz.png" alt="filter"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Output -&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Bike&lt;/span&gt;
&lt;span class="nc"&gt;Truck&lt;/span&gt;
&lt;span class="nc"&gt;Cycle&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we have created a stream of vehicles, filtered the names that have more than 3 letters and displayed the resultant names on the console.&lt;/p&gt;

&lt;h3&gt;
  
  
  Map()
&lt;/h3&gt;

&lt;p&gt;Mapping helps to perform an operation on each element of the stream.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3acinkgpeosaus8lanqn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3acinkgpeosaus8lanqn.png" alt="Image map"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Output -&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="mi"&gt;15&lt;/span&gt;
&lt;span class="mi"&gt;25&lt;/span&gt;
&lt;span class="mi"&gt;35&lt;/span&gt;
&lt;span class="mi"&gt;45&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, the lambda expression &lt;code&gt;eachNumber -&amp;gt; eachNumber + 5&lt;/code&gt; is being used to map each element and increment each number by 5.&lt;/p&gt;

&lt;h3&gt;
  
  
  Sorted()
&lt;/h3&gt;

&lt;p&gt;Sorting arranges elements in a specified order.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ifz5v3jm9ex7joxbll3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2ifz5v3jm9ex7joxbll3.png" alt="Image sorted"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Output -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="mi"&gt;100&lt;/span&gt;
&lt;span class="mi"&gt;500&lt;/span&gt;
&lt;span class="mi"&gt;700&lt;/span&gt;
&lt;span class="mi"&gt;800&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, the &lt;code&gt;sorted()&lt;/code&gt; method has arranged the elements of the numbers stream in ascending order.&lt;/p&gt;

&lt;h3&gt;
  
  
  Distinct()
&lt;/h3&gt;

&lt;p&gt;Distinct method removes the duplicate elements from the stream.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fww633ldf2kxoh1rgn1ql.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fww633ldf2kxoh1rgn1ql.png" alt="Image distinct"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Output -&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Apple&lt;/span&gt;
&lt;span class="nc"&gt;Mango&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, the &lt;code&gt;distinct()&lt;/code&gt; method has removed the duplicate strings from the stream.&lt;/p&gt;

&lt;h2&gt;
  
  
  Terminal Operations
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;Terminal operations are like the toll booth itself - once a vehicle passes the toll booth, it can't go back. Similarly, terminal operations are the final actions on a stream.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A terminal operation is a stream operation that &lt;strong&gt;consumes the elements of a stream and produces a result.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fes2nc94rwpdel9yg5px7.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fes2nc94rwpdel9yg5px7.jpeg" alt="Image toll"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Types of terminal operations include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;forEach&lt;/code&gt; &lt;/li&gt;
&lt;li&gt;&lt;code&gt;reduce&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;count&lt;/code&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  ForEach()
&lt;/h3&gt;

&lt;p&gt;This method is used for performing an action on each element.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftdeel9387crbmpu2qu73.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftdeel9387crbmpu2qu73.png" alt="Image foreach"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Output -&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;Apple&lt;/span&gt;
&lt;span class="nc"&gt;Mango&lt;/span&gt;
&lt;span class="nc"&gt;Banana&lt;/span&gt;
&lt;span class="nc"&gt;Kiwi&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code,  the &lt;code&gt;forEach()&lt;/code&gt; method is used to display the elements of the resultant stream on the console.&lt;/p&gt;

&lt;h3&gt;
  
  
  reduce()
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;&lt;code&gt;reduce()&lt;/code&gt;&lt;/strong&gt; is a terminal operation that combines all elements of the stream into a single result. It takes two parameters: an &lt;strong&gt;identity&lt;/strong&gt; value and a &lt;strong&gt;Binary Operator&lt;/strong&gt; (a function that takes two elements and produces a single result). The &lt;strong&gt;&lt;code&gt;reduce()&lt;/code&gt;&lt;/strong&gt; operation repeatedly applies the Binary Operator to the current result and each element of the stream until all elements have been processed, producing a final result.&lt;/p&gt;

&lt;p&gt;Let’s take an example to find the sum of all numbers in a list.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg8pkxhvu95slqbdueeak.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg8pkxhvu95slqbdueeak.png" alt="Image reduce"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Output -&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="mi"&gt;15&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;strong&gt;&lt;code&gt;reduce&lt;/code&gt;&lt;/strong&gt; operation starts with an initial value of 0 (&lt;strong&gt;&lt;code&gt;identity&lt;/code&gt;&lt;/strong&gt;). For each element in the stream, it adds the element to the current sum (&lt;strong&gt;&lt;code&gt;a + b&lt;/code&gt;&lt;/strong&gt;). The result is the sum of all elements in the stream, which is 15 in this case.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Case - &lt;code&gt;reduce()&lt;/code&gt;&lt;/strong&gt; is useful when you want to aggregate elements of the stream into a single value, such as finding the sum, maximum, minimum, or concatenating strings.&lt;/p&gt;

&lt;h3&gt;
  
  
  count()
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;count()&lt;/code&gt; method returns a &lt;code&gt;long&lt;/code&gt; integer that indicates the number of elements present in the stream.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftv4gzpgh4tjeskiuh9ih.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftv4gzpgh4tjeskiuh9ih.png" alt="Image count"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Output -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="mi"&gt;3&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, the vehicles that has greater than 3 letters were filtered and the &lt;code&gt;count()&lt;/code&gt; method is used to get the number of vehicles in the resultant stream.&lt;/p&gt;

&lt;h2&gt;
  
  
  ForEach() vs Map()
&lt;/h2&gt;

&lt;p&gt;Wondering what’s the difference between &lt;code&gt;forEach()&lt;/code&gt; and &lt;code&gt;map()&lt;/code&gt; methods? Though both these operations seem to be very similar, however they behave and operate differently.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;forEach()&lt;/code&gt; method works similar to the &lt;code&gt;map()&lt;/code&gt;. It iterates over the elements in the stream and performs the specified operation on each element. &lt;/p&gt;

&lt;p&gt;However, the only difference between &lt;code&gt;forEach()&lt;/code&gt; and &lt;code&gt;map()&lt;/code&gt; is - &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;forEach()&lt;/code&gt; method does not return any stream while the &lt;code&gt;map()&lt;/code&gt; method returns a stream.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;forEach&lt;/code&gt;&lt;/strong&gt; is used for performing actions on elements, whereas &lt;strong&gt;&lt;code&gt;map&lt;/code&gt;&lt;/strong&gt; transforms elements.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Case of &lt;code&gt;map()&lt;/code&gt;:&lt;/strong&gt; Use &lt;strong&gt;&lt;code&gt;map&lt;/code&gt;&lt;/strong&gt; when you want to transform the elements of the Stream from one form to another. For example, transforming strings to uppercase, converting objects to specific properties, or performing any other form of transformation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Case of &lt;code&gt;forEach()&lt;/code&gt;:&lt;/strong&gt; Use &lt;strong&gt;&lt;code&gt;forEach&lt;/code&gt;&lt;/strong&gt; when you want to perform an action (such as printing, logging, or updating external states) for each element in the Stream.&lt;/p&gt;

&lt;h2&gt;
  
  
  Closing Thoughts:
&lt;/h2&gt;

&lt;p&gt;Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you’d like us to cover in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.&lt;/p&gt;

&lt;p&gt;Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>softwaredevelopment</category>
      <category>datastructures</category>
    </item>
    <item>
      <title>Semaphores, is that so easy!! The Clothing Store Analogy as a Guide for Beginners</title>
      <dc:creator>Code Craft Club</dc:creator>
      <pubDate>Fri, 22 Sep 2023 15:34:46 +0000</pubDate>
      <link>https://dev.to/codecraftclub/semaphores-is-that-so-easy-the-clothing-store-analogy-as-a-guide-for-beginners-m6h</link>
      <guid>https://dev.to/codecraftclub/semaphores-is-that-so-easy-the-clothing-store-analogy-as-a-guide-for-beginners-m6h</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Introduction to Semaphores&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Semaphores are a synchronization mechanism used in computer science to control access to a shared resource, such as a variable or a section of code usually known as the &lt;code&gt;Critical Section&lt;/code&gt;, in a multithreaded or multi-process environment. They help ensure that multiple threads or processes can access the resource in a coordinated and safe manner.&lt;/p&gt;

&lt;p&gt;Let's use the analogy of a clothing store to understand the concept of semaphores and why they are needed for parallel processing.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The Clothing Store Analogy&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Imagine a clothing store that can only hold a maximum of 5 items inside. There are Tailors (producers) who are continuously creating new items, and customers (consumers) who are eagerly buying them. Here are the key conditions of this analogy:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Store Capacity&lt;/strong&gt;: The store can store a maximum of 5 items at a time.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Continuous Production&lt;/strong&gt;: Producers replenish items as soon as the count decreases to ensure the store doesn't run out of stock.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Continuous Consumption&lt;/strong&gt;: Customers only buy products when items are available in the store.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;No Out-of-Stock&lt;/strong&gt;: At any point, a customer should not encounter an out-of-stock situation.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--dVyFAwvX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rqnvnv5pblh9gjhe0mx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dVyFAwvX--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rqnvnv5pblh9gjhe0mx.png" alt="Clothing Store" width="800" height="675"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now in this scenario, let’s understand the possibilities without the use of semaphores. Since there are multiple producers (tailors) and consumers (customers), everyone would try to access the store concurrently. This can lead to several issues:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Race Conditions&lt;/strong&gt;: Without synchronization, there's no guarantee that one thread won't interrupt another while accessing shared resources like the item count in the store. This can lead to race conditions where the final outcome depends on the order of execution.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Inconsistent State&lt;/strong&gt;: Due to race conditions, the item count in the store may become inconsistent. Producers might add items simultaneously, causing the count to go beyond the store's capacity or even drop below zero, leading to illogical scenarios.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Out-of-Stock Problems&lt;/strong&gt;: Consumers may try to buy items even when none are available, resulting in out-of-stock situations. Conversely, producers may overstock the store, wasting resources.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deadlocks&lt;/strong&gt;: In complex scenarios, without proper synchronization, threads might end up in a deadlock, where they're stuck, unable to proceed because they're all waiting for a resource that won't be released.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s implement the analogy in code and check the issues as discussed above.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Creating the Java Classes&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To implement this analogy, we'll create three Java classes: &lt;strong&gt;&lt;code&gt;Store&lt;/code&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;code&gt;Producer&lt;/code&gt;&lt;/strong&gt;, and &lt;strong&gt;&lt;code&gt;Consumer&lt;/code&gt;&lt;/strong&gt;. &lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The &lt;code&gt;Store&lt;/code&gt; Class (Critical Section)&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;&lt;code&gt;Store&lt;/code&gt;&lt;/strong&gt; class represents our shared resource, the clothing store. It contains the current item count.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--gQ_EZ_PK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uvstfnhv72gpo3km66e7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--gQ_EZ_PK--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uvstfnhv72gpo3km66e7.png" alt="Store class" width="800" height="758"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The &lt;code&gt;Producer&lt;/code&gt; Class&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;&lt;code&gt;Producer&lt;/code&gt;&lt;/strong&gt; class represents tailors who continuously produce items and add them to the store. We are using the &lt;strong&gt;Runnable&lt;/strong&gt; interface to let them run using separate threads.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jlC55qO---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/09rfexur9efzdjtsjv7k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jlC55qO---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/09rfexur9efzdjtsjv7k.png" alt="Producer Class" width="800" height="563"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The &lt;code&gt;Consumer&lt;/code&gt; Class&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;&lt;code&gt;Consumer&lt;/code&gt;&lt;/strong&gt; class represents customers who continuously buy items from the store. We are using the &lt;strong&gt;Runnable&lt;/strong&gt; interface to let them run using separate threads.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--MRPlPO2T--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f794yutx9vm18u6am9i1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--MRPlPO2T--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f794yutx9vm18u6am9i1.png" alt="Consumer class" width="800" height="542"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The &lt;code&gt;Main&lt;/code&gt; Method&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;In the &lt;strong&gt;&lt;code&gt;Main&lt;/code&gt;&lt;/strong&gt; method, we'll create 10 producers and 10 consumers as separate threads and start them to simulate the store scenario.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OmPfCgHt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9y2j4z0n1qemlo2e2usa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OmPfCgHt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9y2j4z0n1qemlo2e2usa.png" alt="Main class" width="800" height="516"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The above program when executed would give rise to &lt;strong&gt;Index out of bounds&lt;/strong&gt; issues. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;With Semaphores → Order is Restored&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Now, let's introduce semaphores to our scenario, and watch as they bring order to the chaos. To implement the semaphores, we need to add the changes in the Main class, Producer class and Consumer class.&lt;/p&gt;

&lt;h3&gt;
  
  
  Adding Semaphores in the Main class
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--D9YjzJW0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zg2to3k7neach35yz6lq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--D9YjzJW0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zg2to3k7neach35yz6lq.png" alt="Main class with Semaphores" width="800" height="604"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Adding Semaphores in the Producer class
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--MwNWGN-v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f04hzmhcr6jkzdh2kyxt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--MwNWGN-v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f04hzmhcr6jkzdh2kyxt.png" alt="Producer class with semaphores" width="800" height="721"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Adding Semaphores in the Consumer class
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--RvibTJ8O--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lqbxdyl3zvjog9uoqq5u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--RvibTJ8O--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lqbxdyl3zvjog9uoqq5u.png" alt="Consumer class with semaphores" width="800" height="701"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With the above modifications by adding semaphores: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mutex Semaphore&lt;/strong&gt;: This ensures exclusive access to the critical section (the store) by allowing only one thread in at a time. This prevents race conditions and ensures that changes to the item count are made one at a time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Controlled Access&lt;/strong&gt;: Producers and consumers must acquire a permit before entering the store (critical section). If the store is full (5 items), producers will wait until a consumer buys something, freeing up space. Similarly, consumers will wait if the store is empty until a producer adds an item.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Consistent State&lt;/strong&gt;: Semaphores ensure that the item count remains consistent and within the store's capacity. Producers and consumers work together harmoniously to maintain the correct item count.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;No Deadlocks&lt;/strong&gt;: Semaphores provide a straightforward mechanism for controlling access, reducing the likelihood of deadlocks. Threads can always access the critical section eventually, avoiding deadlock scenarios.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;In short, Semaphores are just like the traffic cops!!&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Gl_8d8s4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/opclx2wqa2f80i6a7ltm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Gl_8d8s4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/opclx2wqa2f80i6a7ltm.png" alt="Traffic cops" width="800" height="455"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;By using semaphores, we transform our chaotic scenario into a well-behaved system, ensuring a smooth shopping experience for both producers and consumers.&lt;/p&gt;




&lt;h3&gt;
  
  
  Closing Thoughts:
&lt;/h3&gt;

&lt;p&gt;Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you’d like us to cover in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.&lt;/p&gt;

&lt;p&gt;Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>java</category>
      <category>multithreading</category>
      <category>programming</category>
      <category>backenddevelopment</category>
    </item>
    <item>
      <title>Mutex &amp; Race Conditions in Java Multi-Threading made so simple with real-life analogies</title>
      <dc:creator>Code Craft Club</dc:creator>
      <pubDate>Fri, 15 Sep 2023 18:58:50 +0000</pubDate>
      <link>https://dev.to/codecraftclub/mutex-race-conditions-in-java-multi-threading-made-so-simple-with-real-life-analogies-42ni</link>
      <guid>https://dev.to/codecraftclub/mutex-race-conditions-in-java-multi-threading-made-so-simple-with-real-life-analogies-42ni</guid>
      <description>&lt;p&gt;Multithreading is a powerful concept in Java, allowing you to run multiple threads of execution concurrently. However, with great power comes great responsibility, and when multiple threads access shared resources, it can lead to synchronization issues. Let's explore the need for synchronization, the issues that arise without it, and the solutions available in Java.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Need for Synchronization
&lt;/h2&gt;

&lt;p&gt;Imagine you have a bank account with a balance of $100, and two threads are running concurrently: one is trying to withdraw money, and the other is attempting to deposit money.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mXahLqv1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qosx0zf4s8isny3zqseb.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mXahLqv1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qosx0zf4s8isny3zqseb.jpeg" alt="Bank" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Thread A (Withdraw) reads the current balance, which is $100.&lt;/li&gt;
&lt;li&gt;Thread B (Deposit) also reads the same current balance, which is still $100.&lt;/li&gt;
&lt;li&gt;Thread A calculates the new balance after withdrawing $50, resulting in $50.&lt;/li&gt;
&lt;li&gt;Thread B calculates the new balance after depositing $30, resulting in $130.&lt;/li&gt;
&lt;li&gt;Thread A updates the balance to $50.&lt;/li&gt;
&lt;li&gt;Thread B updates the balance to $130.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In this scenario, both threads are not synchronized, and they read and modify the balance concurrently. As a result, the final balance is $130, even though the expected behavior should be a balance of $80 ($100 - $50 + $30).&lt;/p&gt;

&lt;p&gt;In multithreading, synchronization is essential to ensure that threads can safely access shared resources (like variables, data structures, or files) without causing conflicts or inconsistencies.&lt;/p&gt;

&lt;h2&gt;
  
  
  *&lt;strong&gt;&lt;em&gt;Three Reasons for Synchronization Issues&lt;/em&gt;&lt;/strong&gt;*
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Critical Section
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;A critical section in multithreading refers to a section of code or a block of code where multiple threads may access shared resources or data concurrently&lt;/em&gt;&lt;/strong&gt;. To ensure correct and consistent behavior, only one thread should be allowed to execute the critical section at a time while other threads wait their turn. This synchronization is achieved using techniques like locks, mutexes (mutual exclusion), or semaphores.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5IN9Iwcj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nc75kfj4b0gbwn7noohr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5IN9Iwcj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nc75kfj4b0gbwn7noohr.png" alt="Critical Section" width="800" height="426"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Race Conditions
&lt;/h3&gt;

&lt;p&gt;A race condition can be described as a situation where &lt;strong&gt;&lt;em&gt;more than one thread attempts to enter a critical section (a section of code where shared resources are accessed) at the same time&lt;/em&gt;&lt;/strong&gt;, leading to unpredictable and incorrect behavior.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. &lt;strong&gt;Preemptiveness&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Preemptive multitasking as the name suggests “Pre-Emptying”, allows the operating system to interrupt a thread and give control to another.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Synchronization problem occurs only when all the above three conditions are met. &lt;br&gt;
To resolve synchronization issues, we need to address any one condition amongst Critical Section, Race Conditions and Preemptiveness.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Ideal Properties of a Synchronization Solution
&lt;/h2&gt;

&lt;p&gt;A good synchronization solution should possess the following properties:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Mutual Exclusion&lt;/strong&gt;: Only one thread exclusively should have access to the critical section at a time, preventing interference. In other terms, there must not be any race conditions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2CjboO0r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3z5fiyiik0ad8gt3amz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2CjboO0r--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3z5fiyiik0ad8gt3amz.png" alt="Mutual Exclusion" width="800" height="441"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Progress of the Program&lt;/strong&gt;: The synchronization should not lead to deadlock, where threads are blocked indefinitely and bring the entire program to a halt. It should allow other threads (at least one thread) to execute when a thread is waiting.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vocG5HGE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xf48vhj00mge131s0kh7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vocG5HGE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xf48vhj00mge131s0kh7.png" alt="Progress" width="800" height="444"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Bounded Waiting&lt;/strong&gt;: A thread should not have to wait indefinitely to enter a critical section. There should be a limit on waiting time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zaIqCz7n--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/720vcs50iwcp5h6f2veq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zaIqCz7n--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/720vcs50iwcp5h6f2veq.png" alt="Bounded" width="800" height="437"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;No Busy Waiting&lt;/strong&gt;: Busy waiting consumes CPU cycles needlessly. An efficient synchronization solution should not force threads to continuously check for access.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--MAAQZYKk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/umjmfdk66lqopriy7s10.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--MAAQZYKk--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/umjmfdk66lqopriy7s10.png" alt="Busy waiting" width="800" height="429"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  MUTEX (Mutual Exclusion)
&lt;/h2&gt;

&lt;p&gt;A mutex, short for "mutual exclusion," is a synchronization mechanism that serves as a lock to ensure mutual exclusion.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--CR-mMMP3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bdcxwx5ovfn6w9ao41k5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--CR-mMMP3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bdcxwx5ovfn6w9ao41k5.png" alt="Mutex" width="800" height="381"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Properties of a Mutex Lock in Java&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Mutual Exclusion&lt;/strong&gt;: Only one thread can acquire the mutex lock at a time, preventing concurrent access to shared resources.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ownership&lt;/strong&gt;: The thread that acquires the mutex lock is the only one that can release it, ensuring proper resource management.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Blocking&lt;/strong&gt;: If a thread attempts to acquire a locked mutex, it will be blocked until the mutex is released by the owning thread.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Non-busy Waiting&lt;/strong&gt;: Threads waiting for the mutex are not actively spinning in a loop but are put in a waiting state until the mutex is available.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Synchronization in Adder &amp;amp; Subtractor
&lt;/h2&gt;

&lt;p&gt;Let’s understand the need of synchronization with an example of Adder and Subtractor.&lt;/p&gt;

&lt;p&gt;In this code, we will have two classes: &lt;strong&gt;&lt;code&gt;Adder&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;Subtractor&lt;/code&gt;&lt;/strong&gt;. These classes represent two concurrent operations that manipulate a shared resource.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Adder:&lt;/strong&gt; The &lt;strong&gt;&lt;code&gt;Adder&lt;/code&gt;&lt;/strong&gt; class is responsible for adding numbers from 1 to 100 to a shared value.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Subtractor:&lt;/strong&gt; The &lt;strong&gt;&lt;code&gt;Subtractor&lt;/code&gt;&lt;/strong&gt; class is responsible for subtracting numbers from 1 to 100 from the same shared value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's create the classes as follows:&lt;/p&gt;

&lt;h4&gt;
  
  
  The &lt;code&gt;SharedResource&lt;/code&gt; class:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---V0i_m_a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tgenk2ii0px7supcwdxv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---V0i_m_a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tgenk2ii0px7supcwdxv.png" alt="Shared Resource" width="800" height="594"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  The &lt;code&gt;Adder&lt;/code&gt; class:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--5lk5V9oA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hw621incbhlsma8vfk7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--5lk5V9oA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hw621incbhlsma8vfk7.png" alt="Adder" width="800" height="504"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  The &lt;code&gt;Subtractor&lt;/code&gt; class:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--_rXZCjAr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qej1ptrumlctxfc76y6k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--_rXZCjAr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qej1ptrumlctxfc76y6k.png" alt="Subtractor" width="800" height="504"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  The &lt;code&gt;Main&lt;/code&gt; class:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LYKll2yf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rozyb7vdflrh9hi64b3y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LYKll2yf--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rozyb7vdflrh9hi64b3y.png" alt="Main" width="800" height="535"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this code:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;SharedResource&lt;/code&gt;&lt;/strong&gt; is a class that contains the shared value.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;Adder&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;Subtractor&lt;/code&gt;&lt;/strong&gt; are two separate threads that add and subtract values from the shared resource, respectively.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;&lt;code&gt;Main&lt;/code&gt;&lt;/strong&gt; class creates instances of &lt;strong&gt;&lt;code&gt;Adder&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;Subtractor&lt;/code&gt;&lt;/strong&gt;, starts them concurrently, and then waits for them to finish using &lt;strong&gt;&lt;code&gt;join()&lt;/code&gt;&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When you run this code, you'll likely observe that the final shared value is not always 0, which indicates a synchronization issue because the &lt;strong&gt;&lt;code&gt;add&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;subtract&lt;/code&gt;&lt;/strong&gt; operations are not synchronized.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Behavior of the code Without Locks:&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Without any synchronization mechanism (locks), both the &lt;strong&gt;&lt;code&gt;Adder&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;Subtractor&lt;/code&gt;&lt;/strong&gt; threads run concurrently and can access the shared resource simultaneously. This can lead to race conditions, where the order of execution and interleaving of operations between the threads are unpredictable. As a result, the final value of the shared resource can vary each time the program is run.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Implementation for Synchronization:&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;In Java, the &lt;strong&gt;&lt;code&gt;ReentrantLock&lt;/code&gt;&lt;/strong&gt; is a common implementation of a Mutex.&lt;/p&gt;

&lt;p&gt;To make the code synchronous and prevent race conditions, we use &lt;strong&gt;&lt;code&gt;ReentrantLock&lt;/code&gt;&lt;/strong&gt; to protect the critical sections of code, specifically the &lt;strong&gt;&lt;code&gt;add&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;subtract&lt;/code&gt;&lt;/strong&gt; methods in the &lt;strong&gt;&lt;code&gt;SharedResource&lt;/code&gt;&lt;/strong&gt; class. Here's how it's done:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--fLRUL4Ox--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdtyg56q3hpxe21d9kry.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fLRUL4Ox--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdtyg56q3hpxe21d9kry.png" alt="Shared Resource with lock" width="800" height="856"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;By acquiring and releasing the lock using &lt;strong&gt;&lt;code&gt;lock.lock()&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;lock.unlock()&lt;/code&gt;&lt;/strong&gt; respectively, we ensure that only one thread can execute the critical sections of the &lt;strong&gt;&lt;code&gt;add&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;subtract&lt;/code&gt;&lt;/strong&gt; methods at any given time, preventing concurrent interference and ensuring consistent and correct results.&lt;/p&gt;

&lt;p&gt;With these modifications, the code becomes synchronized, and the final shared value will always be 0, as expected, regardless of how many times you run the program.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;&lt;code&gt;ReentrantLock&lt;/code&gt;&lt;/strong&gt; was used, ensuring that only one thread could access the critical sections at a time. This synchronization mechanism resolved race conditions and ensured that the final shared value was always 0, as expected.&lt;/p&gt;

&lt;p&gt;While locks are a common and effective way to achieve synchronization, there are other methods and techniques as well such as &lt;strong&gt;Synchronized Methods, Synchronized Blocks and Semaphores.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Closing Thoughts:
&lt;/h3&gt;

&lt;p&gt;Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you'd like us to cover in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.&lt;/p&gt;

&lt;p&gt;Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>java</category>
      <category>multithreading</category>
      <category>programming</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Multi-Threading in JAVA using Callables</title>
      <dc:creator>Code Craft Club</dc:creator>
      <pubDate>Thu, 14 Sep 2023 14:19:45 +0000</pubDate>
      <link>https://dev.to/codecraftclub/multi-threading-in-java-using-callables-3ke3</link>
      <guid>https://dev.to/codecraftclub/multi-threading-in-java-using-callables-3ke3</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Introduction to Callables&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In multi-threaded programming, we often encounter scenarios where tasks need to be executed concurrently, but they don't necessarily need to return any values. Think of these tasks as workers performing their jobs independently, like chefs work simultaneously to execute their tasks, and they don't need to return any specific information. In such cases, &lt;code&gt;runnables&lt;/code&gt; can be used where there is nothing to return.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzjjyinen3sy22pkqy2ie.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzjjyinen3sy22pkqy2ie.jpeg" alt="Kitchen"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However, there are situations where not only do we need tasks to run concurrently, but we also need them to return some valuable data upon completion. This is where the concept of &lt;code&gt;Callables&lt;/code&gt; comes into play.&lt;/p&gt;

&lt;p&gt;Let’s understand with an example:&lt;/p&gt;

&lt;h4&gt;
  
  
  Online Shopping:
&lt;/h4&gt;

&lt;p&gt;Imagine you are an online shopper placing multiple orders. You want to track the status of each order and get confirmation when each order is successfully processed. This is where the concept of &lt;strong&gt;&lt;code&gt;Callable&lt;/code&gt;&lt;/strong&gt; comes in.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqa6r29y2262myf9u3jsb.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqa6r29y2262myf9u3jsb.jpeg" alt="Shopping"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Callable&lt;/strong&gt; is like each online order you've placed. These are the tasks you care about because you want to track the status of your orders.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Future&lt;/strong&gt; is like the shipping confirmation email you receive for each order. When an order is shipped (the task is completed), you get an email (Future) that tells you the order's status and provides tracking information.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Using Callables in Multi-Threaded Programs
&lt;/h2&gt;

&lt;p&gt;To incorporate &lt;code&gt;Callables&lt;/code&gt; into multi-threaded programs, you can follow these steps:&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 1: Identify Tasks Needing Data Returns
&lt;/h3&gt;

&lt;p&gt;Identify &lt;code&gt;tasks&lt;/code&gt; within your program that require data to be returned upon completion. These tasks are analogous to online shopping orders where you want tracking information.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2: Create Callable Classes
&lt;/h3&gt;

&lt;p&gt;For tasks that need to return data, create classes and implement the &lt;strong&gt;&lt;code&gt;Callable&lt;/code&gt;&lt;/strong&gt; interface. This interface allows tasks to return results or throw exceptions, making it suitable for data-retrieval tasks.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.concurrent.Callable;

class OrderProcessingTask implements Callable&amp;lt;String&amp;gt; {
    private String item;

    public OrderProcessingTask(String item) {
        this.item = item;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 3: Implement the &lt;code&gt;call()&lt;/code&gt; Method
&lt;/h3&gt;

&lt;p&gt;Inside your &lt;code&gt;Callable&lt;/code&gt; class, implement the &lt;strong&gt;&lt;code&gt;call()&lt;/code&gt;&lt;/strong&gt; method, which contains the code for the task and defines the return type for the method. This method represents the work that needs to be done and returns the result upon completion.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override
public String call() throws Exception {
    // Simulate order processing
    Thread.sleep(2000); // Simulating processing time
    return "Order for " + item + " is processed.";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 4: Create a Main Class Using Executor Service
&lt;/h3&gt;

&lt;p&gt;Create a main class that utilizes the &lt;strong&gt;&lt;code&gt;ExecutorService&lt;/code&gt;&lt;/strong&gt; to execute the Callable tasks:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class OnlineShoppingApp {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        // Create order processing tasks
        Callable&amp;lt;String&amp;gt; order1 = new OrderProcessingTask("Product A");
        Callable&amp;lt;String&amp;gt; order2 = new OrderProcessingTask("Product B");
        Callable&amp;lt;String&amp;gt; order3 = new OrderProcessingTask("Product C");

        // Submit tasks to the executor
        Future&amp;lt;String&amp;gt; result1 = executor.submit(order1);
        Future&amp;lt;String&amp;gt; result2 = executor.submit(order2);
        Future&amp;lt;String&amp;gt; result3 = executor.submit(order3);

        // Wait for tasks to complete and retrieve results
        String status1 = result1.get();
        String status2 = result2.get();
        String status3 = result3.get();

        System.out.println(status1);
        System.out.println(status2);
        System.out.println(status3);

        // Shutdown the executor when done
        executor.shutdown();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Understanding the use of &lt;code&gt;Future&lt;/code&gt; with &lt;code&gt;Callable&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;In the main class, we use &lt;strong&gt;&lt;code&gt;Future&lt;/code&gt;&lt;/strong&gt; objects to capture the results of the submitted &lt;strong&gt;&lt;code&gt;Callable&lt;/code&gt;&lt;/strong&gt; tasks. A &lt;strong&gt;&lt;code&gt;Future&lt;/code&gt;&lt;/strong&gt; represents the result of an asynchronous computation, in this case, the result of each order processing task.&lt;/p&gt;

&lt;blockquote&gt;
&lt;h3&gt;
  
  
  Analogy:
&lt;/h3&gt;

&lt;p&gt;In our example scenario of Online Shopping, each order represents a separate task, and we want to keep track of their status and delivery. So:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Callable&lt;/code&gt; is analogous to an online shopping order. Each order represents a task that we want to track.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Future&lt;/code&gt; is like the order confirmation or tracking number we receive after placing an online order. It’s a reference to our order’s status and allows us to retrieve details when the order is processed.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;Just like you can check the status of our online orders using the order number without waiting at the store, we can use &lt;code&gt;Future&amp;lt;&amp;gt;&lt;/code&gt; to check the status and retrieve results from Callable tasks without blocking the program.&lt;/p&gt;

&lt;blockquote&gt;
&lt;/blockquote&gt;

&lt;p&gt;Here's how this works:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;executor.submit(callable)&lt;/code&gt;&lt;/strong&gt; returns a &lt;strong&gt;&lt;code&gt;Future&lt;/code&gt;&lt;/strong&gt; representing the result of the callable task.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;result.get()&lt;/code&gt;&lt;/strong&gt; is called to retrieve the result of the task.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This allows to efficiently manage tasks that return data in a multi-threaded program. The &lt;strong&gt;&lt;code&gt;Future&lt;/code&gt;&lt;/strong&gt; provides a way to obtain the result of the task when it's ready, just like tracking online orders and receiving status updates when the orders are processed.&lt;/p&gt;

&lt;h3&gt;
  
  
  Closing Thoughts:
&lt;/h3&gt;

&lt;p&gt;Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you’d like us to cover in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.&lt;/p&gt;

&lt;p&gt;Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>java</category>
      <category>concurrency</category>
      <category>programming</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>Generics in Java was never this EASY! — A Complete Beginner’s Guide!</title>
      <dc:creator>Code Craft Club</dc:creator>
      <pubDate>Mon, 11 Sep 2023 09:07:49 +0000</pubDate>
      <link>https://dev.to/codecraftclub/generics-in-java-was-never-this-easy-a-complete-beginners-guide-1ghm</link>
      <guid>https://dev.to/codecraftclub/generics-in-java-was-never-this-easy-a-complete-beginners-guide-1ghm</guid>
      <description>&lt;p&gt;Imagine you have a collection of jars, all identical in shape and size, but each one with a unique label. Now, these jars can be used to store a variety of items, from candies to spices, without any confusion. The label on each jar is the key — it tells you exactly what should go inside. Just like these labeled jars simplify your storage needs, Generics in Java are like labels for your code, making it easy to work with multiple data types while keeping things organized.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--DX2elqQ7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/apidnbroli4a8cn8jj1h.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--DX2elqQ7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/apidnbroli4a8cn8jj1h.jpeg" alt="Jars" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What Are Generics?
&lt;/h2&gt;

&lt;p&gt;Generics in Java are like those &lt;strong&gt;labels&lt;/strong&gt; on your jars, but for your code. They allow you to create classes, methods, and interfaces that can work with different data types while ensuring type safety. These labels (or &lt;code&gt;type parameters&lt;/code&gt;) specify what kind of data each container can hold, just like the labels on your jars specify what goes inside.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Need for Generics
&lt;/h3&gt;

&lt;p&gt;Imagine if your jars had no labels. You’d have to open each one to figure out what’s inside. It would be a chaotic mess! Without Generics, your code can end up in a similar mess, with lots of redundancy. You might need to create separate classes for each data type, which is inefficient and prone to errors. Generics come to the rescue, allowing you to create a single, versatile container that can hold various types of data, just like those labeled jars help keep your kitchen organized.&lt;/p&gt;

&lt;h2&gt;
  
  
  Type Parameters and Representation
&lt;/h2&gt;

&lt;p&gt;In Java, generics use type parameters, which are placeholders for specific data types. These type parameters can be represented in two common ways:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Single Letter Convention:&lt;/strong&gt; Typically, single uppercase letters are used to distinguish from regular class or interface names. The most commonly used parameters are&lt;br&gt;
&lt;code&gt;E&lt;/code&gt; - Element (used extensively by the Java Collections Framework)&lt;br&gt;
&lt;code&gt;K&lt;/code&gt; - Key&lt;br&gt;
&lt;code&gt;N&lt;/code&gt; - Number&lt;br&gt;
&lt;code&gt;T&lt;/code&gt; - Type&lt;br&gt;
&lt;code&gt;V&lt;/code&gt; - Value&lt;br&gt;
They don't carry any special meaning; they're just placeholders.&lt;br&gt;
For example, the class &lt;code&gt;java.util.HashMap&amp;lt;K, V&amp;gt;&lt;/code&gt; has two type parameters, &lt;code&gt;K&lt;/code&gt; and &lt;code&gt;V&lt;/code&gt;, representing the type of the keys and values, respectively, stored in the map. The interface &lt;code&gt;java.util.List&amp;lt;E&amp;gt;&lt;/code&gt; has a single type parameter &lt;code&gt;E&lt;/code&gt; representing the type of the elements stored in the list.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Descriptive Names:&lt;/strong&gt; Sometimes, more descriptive names like &lt;code&gt;KeyType&lt;/code&gt; or &lt;code&gt;ValueType&lt;/code&gt; are used for type parameters, especially when clarity is important, just as you might use labels with descriptive names for your jars.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Generic Classes
&lt;/h2&gt;

&lt;p&gt;Now, let’s delve into generic classes with code and explanations.&lt;br&gt;
&lt;em&gt;Syntax of a Generic Class -&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ClassName&amp;lt;T1, T2, ..., Tn&amp;gt; {
    // block of code
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, T1, T2, …, Tn are the comma-separated type variables.&lt;br&gt;
Let’s understand with an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Box&amp;lt;T&amp;gt; {
    private T contents;

    public Box(T contents) {
        this.contents = contents;
    }

    public void printDataType() {
        System.out.println("Type: " + this.contents.getClass().getSimpleName());
    }
}

class Main{
   public static void main(String[] args) {
    Box&amp;lt;Integer&amp;gt; integerBox = new Box&amp;lt;&amp;gt;(42);
  integerBox.printDataType();

    Box&amp;lt;String&amp;gt; stringBox = new Box&amp;lt;&amp;gt;("Hello, Generics!");
  stringBox.printDataType();
}
}

// Output:
// Type: Integer
// Type: String
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, we've defined a generic class &lt;strong&gt;&lt;code&gt;Box&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/strong&gt; that can hold any type of object, where &lt;strong&gt;&lt;code&gt;T&lt;/code&gt;&lt;/strong&gt; is our type parameter. The &lt;strong&gt;&lt;code&gt;printDataType&lt;/code&gt;&lt;/strong&gt; method prints the type of the contents stored in the &lt;strong&gt;&lt;code&gt;Box&lt;/code&gt;&lt;/strong&gt; using &lt;strong&gt;&lt;code&gt;getClass().getSimpleName()&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In the &lt;strong&gt;&lt;code&gt;main&lt;/code&gt;&lt;/strong&gt; method, we create instances of &lt;strong&gt;&lt;code&gt;Box&lt;/code&gt;&lt;/strong&gt; for both &lt;strong&gt;&lt;code&gt;Integer&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;String&lt;/code&gt;&lt;/strong&gt; types and call the &lt;strong&gt;&lt;code&gt;printDataType&lt;/code&gt;&lt;/strong&gt; method on each of them. This should print the respective types of the contents stored in the &lt;strong&gt;&lt;code&gt;Box&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Analogy -
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Just like your labeled jars can hold different items, the &lt;strong&gt;&lt;code&gt;Box&lt;/code&gt;&lt;/strong&gt; class can hold different data types. The type parameter &lt;strong&gt;&lt;code&gt;T&lt;/code&gt;&lt;/strong&gt; acts like the label, ensuring that you only put compatible items inside.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Generic Methods
&lt;/h2&gt;

&lt;p&gt;Now, let’s delve into generic methods within a generic class.&lt;br&gt;
&lt;em&gt;Syntax of a Generic Method:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;T1, T2, ..., Tn&amp;gt; returnType methodName(parameters) {
    // block of code
}

// Example Syntax -

  //Example 1
  public &amp;lt;T&amp;gt; void methodName(T obj) {
      // block of code
  }

  //Example 2
  public static &amp;lt;T, N&amp;gt; T methodName(T obj, N num) {
      // block of code
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s understand with an example now:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Box&amp;lt;T&amp;gt; {
    private T contents;

    public Box(T contents) {
        this.contents = contents;
    }

    public T getContents(){ //method returns T type
      return this.contents;
    }
}

class Main{
   public static void main(String[] args) {
    Box&amp;lt;Integer&amp;gt; integerBox = new Box&amp;lt;&amp;gt;(42);
  System.out.println("Method Returned:" + integerBox.getContents());

    Box&amp;lt;String&amp;gt; stringBox = new Box&amp;lt;&amp;gt;("Hello, Generics!");
  System.out.println("Method Returned:" + stringBox.getContents());
}
}

// Output -
// Method Returned:42
// Method Returned:Hello, Generics!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, we have a generic class &lt;strong&gt;&lt;code&gt;Box&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/strong&gt; with a constructor that accepts an object of type &lt;strong&gt;&lt;code&gt;T&lt;/code&gt;&lt;/strong&gt; and a &lt;strong&gt;&lt;code&gt;getContents&lt;/code&gt;&lt;/strong&gt; method that returns an object of type &lt;strong&gt;&lt;code&gt;T&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;integerBox&lt;/code&gt; object is created with an &lt;strong&gt;Integer&lt;/strong&gt; type parameter and the &lt;code&gt;stringBox&lt;/code&gt; object is created with a &lt;strong&gt;String&lt;/strong&gt; type parameter.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;main()&lt;/code&gt; method, we are calling the &lt;code&gt;getContents()&lt;/code&gt; method on both objects and displayed the returned values on the console.&lt;/p&gt;

&lt;h2&gt;
  
  
  Generic Interfaces
&lt;/h2&gt;

&lt;p&gt;Similar to creating Generic Classes and Generic Methods, we can also create interfaces in Java that can be used with any type of data by using generics. This type of method is known as a Generic Interface.&lt;br&gt;
&lt;em&gt;Syntax of a Generic Interface:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface InterfaceName&amp;lt;T1, T2, ..., Tn&amp;gt; {
    // block of code
}

class ClassName&amp;lt;T1, T2, ..., Tn&amp;gt; implements InterfaceName&amp;lt;T1, T2, ..., Tn&amp;gt; {
    // block of code
}



// Example Syntax -

interface Pair&amp;lt;K, V&amp;gt; {
    K getKey();
    V getValue();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Pair&lt;/code&gt; is a generic interface defining two type parameters, &lt;code&gt;K&lt;/code&gt; and &lt;code&gt;V&lt;/code&gt;. &lt;br&gt;
Implementing classes specify the actual types:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Pair&amp;lt;K, V&amp;gt; {
    K getKey();
    V getValue();
}


class OrderedPair&amp;lt;K, V&amp;gt; implements Pair&amp;lt;K, V&amp;gt; {
    private K key;
    private V value;

    public OrderedPair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }
}

class Main{
  public static void main(String[] args){
    OrderedPair&amp;lt;String, Integer&amp;gt; obj = new OrderedPair&amp;lt;&amp;gt;("Mobile No", 999999999);
    System.out.println("Key: " + obj.getKey());
    System.out.println("Value: " + obj.getValue());
  }
}

// Output -
// Key: Mobile No
// Value: 999999999
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, we have defined a generic interface &lt;strong&gt;&lt;code&gt;Pair&amp;lt;K, V&amp;gt;&lt;/code&gt;&lt;/strong&gt; with two type parameters, &lt;strong&gt;&lt;code&gt;K&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;V&lt;/code&gt;&lt;/strong&gt;, which define methods &lt;strong&gt;&lt;code&gt;getKey&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;getValue&lt;/code&gt;&lt;/strong&gt;. Then, we have implemented this interface with the &lt;strong&gt;&lt;code&gt;OrderedPair&amp;lt;K, V&amp;gt;&lt;/code&gt;&lt;/strong&gt; class, where &lt;strong&gt;&lt;code&gt;K&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;V&lt;/code&gt;&lt;/strong&gt; are specific types (in this case, &lt;strong&gt;&lt;code&gt;String&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;Integer&lt;/code&gt;&lt;/strong&gt;).&lt;/p&gt;

&lt;p&gt;In the &lt;strong&gt;&lt;code&gt;main&lt;/code&gt;&lt;/strong&gt; method, we create an instance of &lt;strong&gt;&lt;code&gt;OrderedPair&amp;lt;String, Integer&amp;gt;&lt;/code&gt;&lt;/strong&gt; with values &lt;code&gt;"Mobile No"&lt;/code&gt; and &lt;code&gt;999999999&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bounded Types
&lt;/h2&gt;

&lt;p&gt;Now, imagine if you wanted to limit the types that can be used with generics, just like specifying that a jar is for storing only chocolates. This is where bounded types come in.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--yGodIH4P--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mq75lk67zre1zb2pzmj.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--yGodIH4P--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mq75lk67zre1zb2pzmj.jpeg" alt="Chocolate jar" width="800" height="800"&gt;&lt;/a&gt;&lt;br&gt;
As we saw above of how we can create generic classes, interfaces, and methods that can work with any data type, however, sometimes we may want to limit the data types that can be used with a generic to a specific set of types. In these cases, we can use bounded types by specifying the upper bound type parameter with the extends keyword.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Syntax of a Bounded Types:&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;T extends A&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the type parameter &lt;code&gt;T&lt;/code&gt; can only accept data types that are of type &lt;code&gt;A&lt;/code&gt; or any classes or interfaces that extends &lt;code&gt;A&lt;/code&gt;.&lt;br&gt;
Let’s understand with an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class NumberContainer&amp;lt;T extends Number&amp;gt; {
    private T value;

    public NumberContainer(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }
}

class Main{
  public static void main(String[] args) {
    NumberContainer&amp;lt;Integer&amp;gt; intContainer = new NumberContainer&amp;lt;&amp;gt;(42);
    Integer intValue = intContainer.getValue(); // Works fine
    System.out.println(intValue);

    NumberContainer&amp;lt;Double&amp;gt; doubleContainer = new NumberContainer&amp;lt;&amp;gt;(3.14);
    Double doubleValue = doubleContainer.getValue(); // Works fine
    System.out.println(doubleValue);
    }
}

// Output -
// 42
// 3.14
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, &lt;strong&gt;&lt;code&gt;NumberContainer&lt;/code&gt;&lt;/strong&gt; is a generic class that can hold any type that extends the &lt;strong&gt;&lt;code&gt;Number&lt;/code&gt;&lt;/strong&gt; class, which includes numeric types such as &lt;strong&gt;&lt;code&gt;Integer&lt;/code&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;code&gt;Double&lt;/code&gt;&lt;/strong&gt;, and &lt;strong&gt;&lt;code&gt;Float&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;We create &lt;strong&gt;&lt;code&gt;NumberContainer&lt;/code&gt;&lt;/strong&gt; instances for &lt;strong&gt;&lt;code&gt;Integer&lt;/code&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;code&gt;Double&lt;/code&gt;&lt;/strong&gt; types and successfully store and retrieve numeric values from them.&lt;/p&gt;

&lt;h3&gt;
  
  
  Failing Scenario in Bounded Types
&lt;/h3&gt;

&lt;p&gt;Now, let’s see a failing scenario for the above example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    NumberContainer&amp;lt;String&amp;gt; stringContainer = new NumberContainer&amp;lt;&amp;gt;("Hello"); // Compilation error!
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this scenario, we attempt to create a &lt;strong&gt;&lt;code&gt;NumberContainer&lt;/code&gt;&lt;/strong&gt; for the &lt;strong&gt;&lt;code&gt;String&lt;/code&gt;&lt;/strong&gt; type, which is not a numeric type. This results in a compilation error because it violates the constraint that the type must extend &lt;strong&gt;&lt;code&gt;Number&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;So, in this example, bounded types ensure that the container only works with numeric types and prevents non-numeric types from being stored in it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In summary, generics in Java are like labeled jars, making it easy to understand, organize, and work with multiple data types in your code. Whether you're working with classes, methods, or interfaces, generics allow you to create more versatile and reliable code. So, just like those labeled jars in your kitchen, generics help you keep your Java code neatly organized and easy to grasp.&lt;/p&gt;

&lt;h3&gt;
  
  
  Closing Thoughts:
&lt;/h3&gt;

&lt;p&gt;Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you’d like us to cover in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.&lt;/p&gt;

&lt;p&gt;Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.&lt;/p&gt;

&lt;p&gt;Happy coding!&lt;/p&gt;

</description>
      <category>java</category>
      <category>oops</category>
      <category>programming</category>
      <category>generics</category>
    </item>
    <item>
      <title>Understanding Executors and Thread Pools in Java</title>
      <dc:creator>Code Craft Club</dc:creator>
      <pubDate>Sat, 09 Sep 2023 09:39:10 +0000</pubDate>
      <link>https://dev.to/codecraftclub/understanding-executors-and-thread-pools-in-java-gge</link>
      <guid>https://dev.to/codecraftclub/understanding-executors-and-thread-pools-in-java-gge</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;The Car Manufacturing Factory Analogy&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Imagine a car manufacturing factory with multiple production lines, each line representing a thread. These production lines work in parallel to assemble cars. However, there's a queue of customer orders that need to be processed.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Z8ImBtKm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cb68bu820s6qslzsp11.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Z8ImBtKm--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cb68bu820s6qslzsp11.jpeg" alt="Car Factory" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;The Challenge&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Overflow of Orders&lt;/strong&gt;: The factory receives a constant stream of customer orders, all queued up. Each order needs to go through the assembly lines to be completed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;One Order, One Line&lt;/strong&gt;: Initially, the factory's approach is to assign each order to a separate production line. This means if there are too many orders, the factory must have an enormous number of production lines, which is impractical.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Context Switching Chaos&lt;/strong&gt;: With so many production lines, they keep switching back and forth between tasks, like changing tools on a workstation. This context switching is time-consuming and doesn't contribute directly to building cars.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Thread Pools to the Rescue&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To address these issues, the factory introduces the concept of a thread pool:&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;1. Creating a Thread Pool&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;In Java, the factory installs a system that manages the production lines efficiently:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

ExecutorService threadPool = Executors.newFixedThreadPool(5);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, they establish a thread pool with, say, five production lines (threads).&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;2. Efficient Order Handling&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Now, when new customer orders arrive, they're sent to the thread pool for processing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;threadPool.execute();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. &lt;strong&gt;Efficient Use of Resources&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The thread pool optimizes the production lines (threads) as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It reuses the same production lines for different orders.&lt;/li&gt;
&lt;li&gt;When one order (task) is complete, the production line (thread) becomes available for the next order.&lt;/li&gt;
&lt;li&gt;This prevents the need to create and dismantle production lines for every order, reducing wasted time and effort.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In summary, just as a car manufacturing factory streamlined its production lines by using a &lt;code&gt;thread pool&lt;/code&gt;, software applications benefit from &lt;code&gt;thread pools&lt;/code&gt; and &lt;code&gt;executors&lt;/code&gt;. Thread pools help manage resources efficiently, avoid excessive context switching, and ensure that tasks are processed in an organized and effective manner.&lt;/p&gt;

&lt;h1&gt;
  
  
  Implementation example of a Thread Pool
&lt;/h1&gt;

&lt;p&gt;Here's an example of creating a task class (analogous to a car assembly task) and passing it to the thread pool using &lt;strong&gt;&lt;code&gt;execute()&lt;/code&gt;&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class CarAssemblyTask implements Runnable {
    @Override
    public void run() {
        // Simulate car assembly process
        System.out.println("Car is being assembled on production line " + Thread.currentThread().getName());
    }
}

public class CarFactory {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);

        for (int i = 0; i &amp;lt; 10; i++) {
            threadPool.execute(new CarAssemblyTask());
        }

        // Shutdown the thread pool when done
        threadPool.shutdown();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we've created a CarAssemblyTask class that implements the Runnable interface. We then submit instances of this task class to the thread pool using execute(). Each task represents the assembly of a car on one of the production lines. The thread pool efficiently manages these tasks, and the production lines are reused for different orders.&lt;/p&gt;

&lt;p&gt;To implement the Thread Pool, we have used &lt;code&gt;newFixedThreadPool()&lt;/code&gt; in the above code that allows us to create a fixed number of threads inside a thread pool. Apart from using the above mentioned &lt;code&gt;newFixedThreadPool()&lt;/code&gt;, Java also provides cached Thread Pool which is implemented as &lt;code&gt;Executors.newCachedThreadPool()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a Cached Thread Pool?
&lt;/h2&gt;

&lt;p&gt;This method creates a thread pool that dynamically adjusts the number of threads based on the workload. It's often used for tasks where the number of tasks is not known in advance, or tasks are short-lived.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Characteristics&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It starts with no threads and creates new threads as needed to accommodate incoming tasks.&lt;/li&gt;
&lt;li&gt;If a thread becomes idle for a certain period (typically 60 seconds), it may be terminated to free up resources.&lt;/li&gt;
&lt;li&gt;There is no fixed limit on the number of threads; it can grow as needed.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  How to choose between Cached Thread Pool and Fixed Thread Pool?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use &lt;code&gt;newCachedThreadPool()&lt;/code&gt;&lt;/strong&gt; when you have a highly variable workload, where the number of tasks can fluctuate widely, and you want the thread pool to adapt dynamically. This is common for short, bursty tasks.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use &lt;code&gt;newFixedThreadPool(n)&lt;/code&gt;&lt;/strong&gt; when you want to restrict the concurrency to a specific number of threads, ensuring that you don't overload the system with too many threads. This is appropriate for tasks with a more predictable workload and when you want to control resource usage.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Closing Thoughts:
&lt;/h2&gt;

&lt;p&gt;Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you’d like us to cover in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.&lt;/p&gt;

&lt;p&gt;Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.&lt;/p&gt;

</description>
      <category>java</category>
      <category>programming</category>
      <category>performance</category>
      <category>multithreading</category>
    </item>
    <item>
      <title>Simplifying Java Multithreading (Runnable interface) with a Construction Analogy</title>
      <dc:creator>Code Craft Club</dc:creator>
      <pubDate>Fri, 08 Sep 2023 18:31:17 +0000</pubDate>
      <link>https://dev.to/codecraftclub/simplifying-java-multithreading-runnable-interface-with-a-construction-analogy-n3</link>
      <guid>https://dev.to/codecraftclub/simplifying-java-multithreading-runnable-interface-with-a-construction-analogy-n3</guid>
      <description>&lt;h1&gt;
  
  
  &lt;strong&gt;Multi-Threaded Program in Java -&lt;/strong&gt;
&lt;/h1&gt;

&lt;p&gt;Imagine you're in a kitchen, trying to prepare a meal. You have a single cutting board and knife, and you need to chop vegetables, boil pasta, and cook a sauce all at the same time. If you were to do each task one after the other, it would take a long time to finish the entire meal.&lt;/p&gt;

&lt;p&gt;Now, let's relate this to programming in Java:&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Single Threaded Programming:&lt;/strong&gt;:
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0yGRe5wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/826uyexqga957jvnewy3.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0yGRe5wz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/826uyexqga957jvnewy3.jpeg" alt="Single chef" width="800" height="800"&gt;&lt;/a&gt;&lt;br&gt;
This is like having only one chef in the kitchen doing all the cooking. The chef starts chopping vegetables, then waits for that to finish, then starts boiling pasta, and so on. It's slow and not very efficient.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Multi-Threaded Programming:&lt;/strong&gt;:
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1MCmTPS8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9506ozssoz35dygfeesf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1MCmTPS8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9506ozssoz35dygfeesf.png" alt="Multiple chefs" width="800" height="800"&gt;&lt;/a&gt;&lt;br&gt;
In this case, it's as if you have multiple chefs in the kitchen, each with their own cutting board and knife. They can work on different tasks simultaneously. One chef can chop vegetables, another can boil pasta, and another can work on the sauce, all at the same time. This makes the cooking process much faster and more efficient.&lt;/p&gt;

&lt;p&gt;In Java, &lt;code&gt;multi-threaded programming&lt;/code&gt; allows you to have multiple &lt;code&gt;"threads"&lt;/code&gt; (similar to chefs) running concurrently within a program. Each thread can perform a specific task independently, and they can work together to complete a larger task more quickly, just like the chefs in the kitchen. This can lead to better performance and responsiveness in Java applications, especially when dealing with tasks that can be done simultaneous&lt;/p&gt;
&lt;h1&gt;
  
  
  &lt;strong&gt;How to create a Multi-Threaded Program -&lt;/strong&gt;
&lt;/h1&gt;

&lt;blockquote&gt;
&lt;p&gt;When thinking of creating a Multi-Threaded Program, never think in terms of what Threads you need to create!&lt;br&gt;
Rather think in terms of what TASKS that needs to be done in parallel.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s understand the steps to create a multi-threaded program by taking an analogy of a construction site with different workers such as painters, carpenters, electricians etc. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--A8tEGS_L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dpa4zguy5qw19jtr0xlo.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--A8tEGS_L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dpa4zguy5qw19jtr0xlo.jpeg" alt="construction site" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Steps to create:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Let's explore the simple steps to create a multi-threaded program now.&lt;/p&gt;
&lt;h3&gt;
  
  
  1. &lt;strong&gt;Define Task Classes&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Create a &lt;code&gt;class&lt;/code&gt; for each &lt;code&gt;task&lt;/code&gt; you want to perform. Think of these classes as workers, and name them as &lt;strong&gt;nouns&lt;/strong&gt; to represent the tasks they'll handle.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt; Imagine you're managing a construction site. You have different types of workers like "Carpenter," "Painter," and "Electrician" for specific jobs.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;
  
  
  2. &lt;strong&gt;Implement the Runnable Interface&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;For every task class, implement the &lt;strong&gt;&lt;code&gt;Runnable&lt;/code&gt;&lt;/strong&gt; interface. This ensures that each class has a &lt;strong&gt;&lt;code&gt;run&lt;/code&gt;&lt;/strong&gt; method, which will contain the code for the task.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt; Think of the &lt;strong&gt;&lt;code&gt;Runnable&lt;/code&gt;&lt;/strong&gt; interface as a set of instructions that every worker (task class) must follow&lt;/p&gt;


&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CarpenterTask implements Runnable {
    public void run() {
        // Code for carpentry work
    }
}

class PainterTask implements Runnable {
    public void run() {
        // Code for painting work
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  3. &lt;strong&gt;Code Task Logic&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Inside each task's &lt;strong&gt;&lt;code&gt;run&lt;/code&gt;&lt;/strong&gt; method, write the code that the task needs to perform. This is where you specify what each worker should do.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt; In our construction site, the &lt;strong&gt;&lt;code&gt;run&lt;/code&gt;&lt;/strong&gt; method of the &lt;code&gt;CarpenterTask&lt;/code&gt; class would contain the actual carpentry work instructions.&lt;/p&gt;


&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CarpenterTask implements Runnable {
    public void run() {
        System.out.println("The carpenter is drilling and fixing screws");
    }
}

class PainterTask implements Runnable {
    public void run() {
        System.out.println("The Painter is painting the walls and windows");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  4. &lt;strong&gt;Create Task Instances&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Instantiate the task classes wherever you want to start a new thread for that task. Think of this as hiring a worker for a specific job.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt; You hire a carpenter when you need carpentry work and a painter when you need painting.&lt;/p&gt;


&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Main{
    public static void main(String[] args){

        //Create the instances of the tasks in the main 
        CarpenterTask carpenter = new CarpenterTask();
        PainterTask painter = new PainterTask();

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  5. &lt;strong&gt;Create Thread Objects&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Create &lt;code&gt;thread&lt;/code&gt; objects for each task instance you created. &lt;code&gt;Threads&lt;/code&gt; are like supervisors that manage the workers (task instances).&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt; You assign a supervisor to each worker to oversee their tasks.&lt;/p&gt;


&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Main{
    public static void main(String[] args){

        //Create the instances of the tasks in the main 
        CarpenterTask carpenter = new CarpenterTask();
        PainterTask painter = new PainterTask();

        //Create the Thread Objects
        Thread carpenterThread = new Thread(carpenter);
        Thread painterThread = new Thread(painter);

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  6. &lt;strong&gt;Start the Threads&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Finally, start the threads using the &lt;strong&gt;&lt;code&gt;start()&lt;/code&gt;&lt;/strong&gt; method. This kicks off the tasks, and the workers (threads) begin working concurrently.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Analogy:&lt;/strong&gt; You tell the supervisors to start overseeing their workers, and each worker begins their assigned task.&lt;/p&gt;


&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class Main{
    public static void main(String[] args){

        //Create the instances of the tasks in the main 
        CarpenterTask carpenter = new CarpenterTask();
        PainterTask painter = new PainterTask();

        //Create the Thread Objects
        Thread carpenterThread = new Thread(carpenter);
        Thread painterThread = new Thread(painter);

        //Start the threads
        carpenterThread.start();
        painterThread.start();

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;With these steps, you've created a multi-threaded program in Java where different tasks are performed concurrently, just like different workers at a construction site simultaneously working on carpentry and painting tasks.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;How to Check Thread Names in Java?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In a multi-threaded Java program, you can easily obtain the name of the currently executing thread by calling &lt;strong&gt;&lt;code&gt;Thread.currentThread().getName()&lt;/code&gt;&lt;/strong&gt;. This allows you to identify which thread is executing a particular task. &lt;/p&gt;

&lt;p&gt;Let's see how to do this in the context of our Carpenter and Painter tasks:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CarpenterTask implements Runnable {
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("Carpenter task is being executed by thread: " + threadName);
        // Code for carpentry work
    }
}

class PainterTask implements Runnable {
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println("Painter task is being executed by thread: " + threadName);
        // Code for painting work
    }
}

//Expcted Output -
//Carpenter task is being executed by thread: Thread-0
//Painter task is being executed by thread: Thread-1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we've added lines to print the thread name within each task's &lt;strong&gt;&lt;code&gt;run&lt;/code&gt;&lt;/strong&gt; method using &lt;strong&gt;&lt;code&gt;Thread.currentThread().getName()&lt;/code&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In this example, "&lt;code&gt;Thread-0&lt;/code&gt;" represents the thread executing the Carpenter task, and "&lt;code&gt;Thread-1&lt;/code&gt;" represents the thread executing the Painter task. The thread names are generated automatically by Java, and they typically have a format like "&lt;code&gt;Thread-X&lt;/code&gt;," where X is a unique identifier for each thread.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Closing Thoughts:&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Thank you for reading our blog. We appreciate your time and interest in our content. If you have any questions, feedback, or topics you'd like us to cover in our future articles, please feel free to leave a comment below. Your input is valuable, and it helps us create content that matters to you.&lt;/p&gt;

&lt;p&gt;Stay connected with us for more insightful articles on various topics related to technology, programming, and much more.&lt;/p&gt;

</description>
      <category>java</category>
      <category>javathreads</category>
      <category>multithreading</category>
      <category>parallelprogramming</category>
    </item>
  </channel>
</rss>
