<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chandan Kumar Barik on Medium]]></title>
        <description><![CDATA[Stories by Chandan Kumar Barik on Medium]]></description>
        <link>https://medium.com/@chandanwrites?source=rss-533a5573e9df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_uHHn2GnL-v5csYiOnBJKQ.jpeg</url>
            <title>Stories by Chandan Kumar Barik on Medium</title>
            <link>https://medium.com/@chandanwrites?source=rss-533a5573e9df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 00:40:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chandanwrites/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Design Patterns JAVA | Singleton Pattern]]></title>
            <link>https://medium.com/@chandanwrites/design-patterns-java-singleton-pattern-707a60b5bfe2?source=rss-533a5573e9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/707a60b5bfe2</guid>
            <category><![CDATA[design-pattern-in-java]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[singleton]]></category>
            <dc:creator><![CDATA[Chandan Kumar Barik]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 09:45:49 GMT</pubDate>
            <atom:updated>2024-04-03T09:45:49.906Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Patterns ? What are they ?</h3><p>Imagine you’re faced with <em>a recurring problem</em> in your daily routine: “<em>getting ready for work”</em>.</p><p>You find yourself following <em>a set of steps</em> every morning, from making coffee to choosing your outfit. These steps form a <em>pattern</em> — a reliable sequence of actions <strong>to solve a familiar problem efficiently</strong>.</p><p>In the same way, design patterns offer <strong><em>pre-established solutions</em> <em>to common problems</em></strong> in software development. They’re like <em>blueprints</em> for crafting code, helping developers tackle challenges with ease.</p><p><strong>Types of Design Patterns:</strong></p><ol><li><strong>Creational Patterns</strong>: These patterns focus on the best way to create instances of objects. Just like how a manufacturer might use a mold to mass-produce identical products, <em>creational patterns provide guidelines for creating objects in a structured and efficient manner</em>. Example: Factory Method Pattern : like a factory producing different types of cars based on customer specifications.</li><li><strong>Structural Patterns</strong>: Structural patterns help organize code by defining <em>relationships between classes and objects</em>. They’re like the architectural framework of a building, ensuring stability and coherence in the structure. Example: Adapter Pattern : similar to using a power adapter to connect electronic devices with different plug types.</li><li><strong>Behavioral Patterns</strong>: These patterns govern <em>how objects interact and communicate with each other</em>. They’re like the unwritten rules of social etiquette, guiding smooth interactions between individuals. Example: Observer Pattern : akin to subscribing to a newsletter to receive updates whenever new content is published.</li></ol><p>These design patterns offer developers a systematic approach to solving problems, enhancing code readability, maintainability, and scalability. Just as you rely on your morning routine to kickstart your day efficiently, mastering design patterns empowers developers to streamline their software development process and deliver high-quality solutions effectively.</p><blockquote><strong>TL;DR</strong>: Design patterns are predefined solutions to common software development problems, aiding developers in writing efficient and maintainable code.</blockquote><p>The Gang of Four (GoF) [<em>Are a set of 23 established solutions for common object-oriented design problems, categorized into creational, structural, and behavioral patterns.</em>]design patterns include the following creational patterns:</p><ol><li><strong>Singleton Pattern</strong>: Ensures a class has only one instance and provides a global point of access to it.</li><li><strong>Factory Method Pattern</strong>: Defines an interface for creating objects in a superclass, allowing subclasses to alter the type of objects that will be created.</li><li><strong>Abstract Factory Pattern</strong>: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.</li><li><strong>Builder Pattern</strong>: Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.</li><li><strong>Prototype Pattern</strong>: Creates new objects by copying an existing object, allowing for the creation of new instances without knowledge of their concrete types.</li></ol><h3>Singleton Pattern :</h3><p><strong>Problem Statement </strong>: It revolves around the need to ensure that a class has only one instance throughout the application’s lifecycle. This is crucial in scenarios where multiple instances could lead to issues such as inconsistent behavior, inefficient resource usage, or violation of system constraints.</p><p><strong>Design Considerations and Solution Overview</strong> :</p><p>So, we need to access the only instance of that class using a method or field. Also, the instance is now available globally, which in turns means when you add state to a singleton, it becomes part of the global state of your application. This means that the state is shared across all components that interact with the singleton instance. In object-oriented programming, “state” refers to the data or attributes that describe the characteristics or properties of an object. By adding state to a singleton, you’re essentially introducing shared data that can be accessed and modified by any part of your application. This shared state can affect the behavior of your application and must be managed carefully to ensure consistency and avoid conflicts.</p><p>For example, let’s say you have a singleton class representing a database connection manager. If you add a connection pool as state to this singleton, it becomes part of the global state of your application. Any component that needs to interact with the database will use the same connection pool managed by the singleton instance. Changes to the connection pool made by one component will affect all other components that use the singleton instance, potentially leading to unexpected behavior or conflicts.</p><p>Therefore, when designing a singleton with state, it’s important to carefully consider how the shared state will be accessed, modified, and synchronized to ensure the correct behavior of your application. Additionally, you should strive to minimize the amount of shared state in your application and encapsulate it within the singleton instance to maintain encapsulation and reduce coupling between components.</p><p>How to create singletons ? There are two ways :</p><ol><li>Eager Initializations : Create singleton as soon as the class is loaded.</li><li>Lazy Initializations : Created later on need.</li></ol><p><strong>Eager Initializations</strong> :</p><pre>public class Singleton {<br><br>    // Private static instance initialized eagerly<br>    private static final Singleton instance = new Singleton();<br><br>    // Private constructor to prevent instantiation from outside<br>    private Singleton() {<br>        // Constructor implementation<br>    }<br><br>    // Static method to get the singleton instance<br>    public static Singleton getInstance() {<br>        return instance;<br>    }<br><br>    // Other methods of the Singleton class<br>}<br><br><br><br><br>public class Main {<br>    public static void main(String[] args) {<br>        // Get the singleton instance<br>        Singleton singleton = Singleton.getInstance();<br><br>        // Access the singleton instance and print a message<br>        System.out.println(&quot;Singleton instance created: &quot; + singleton);<br><br>        // Try to create another instance (which is not possible)<br>        // Singleton anotherInstance = new Singleton(); // Compilation error: constructor Singleton() is private<br>    }<br>}</pre><p><strong>Lazy Initializations</strong> :</p><pre>public class LazySingleton {<br>    // Private static instance initialized lazily<br>    // We didn&#39;t initialise it<br>    private static LazySingleton instance;<br><br>    // Private constructor to prevent instantiation from outside<br>    private LazySingleton() {<br>        // Constructor implementation<br>    }<br><br>    // Static method to get the singleton instance with lazy initialization<br>    public static synchronized LazySingleton getInstance() {<br>        if (instance == null) {<br>            instance = new LazySingleton();<br>        }<br>        return instance;<br>    }<br><br>    // Other methods of the LazySingleton class<br>}<br><br><br>// Or we can go for below implementation <br><br>public class DoubleCheckedLockingSingleton {<br>    // Private volatile static instance variable initialized lazily<br>    /*<br>      The volatile keyword ensures that any write to the instance variable is immediately visible to all threads. Without volatile, changes made to variables may not be visible to other threads immediately, leading to potential inconsistencies or incorrect behavior in a multi-threaded environment.<br>    */<br>    private static volatile DoubleCheckedLockingSingleton instance;<br><br>    // Private constructor to prevent instantiation from outside<br>    private DoubleCheckedLockingSingleton() {<br>        // Constructor implementation<br>    }<br><br>    // Static method to get the singleton instance with double-checked locking<br>    public static DoubleCheckedLockingSingleton getInstance() {<br>        if (instance == null) {<br>            synchronized (DoubleCheckedLockingSingleton.class) {<br>                if (instance == null) {<br>                    instance = new DoubleCheckedLockingSingleton();<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br><br>    // Other methods of the DoubleCheckedLockingSingleton class<br>}</pre><p>To avoid going into synchronisation, there is an alternate way to do Lazy Singleton :</p><p><strong>The Lazy Initialization Holder Implementation</strong> is a variation of the Singleton Pattern that achieves lazy initialization in a thread-safe manner without using explicit synchronization. It relies on the class loader mechanism for thread safety.</p><pre>public class LazyInitializedSingleton {<br>    // Private constructor to prevent instantiation from outside<br>    private LazyInitializedSingleton() {<br>        // Constructor implementation<br>    }<br><br>    // Static inner class to hold the singleton instance<br>    private static class SingletonHolder {<br>        // Static final variable initialized lazily<br>        private static final LazyInitializedSingleton INSTANCE = new LazyInitializedSingleton();<br>    }<br><br>    // Method to get the singleton instance<br>    public static LazyInitializedSingleton getInstance() {<br>        return SingletonHolder.INSTANCE;<br>    }<br><br>    // Other methods of the LazyInitializedSingleton class<br>}<br><br><br>public class Main {<br>    public static void main(String[] args) {<br>        // Get the singleton instance<br>        LazyInitializedSingleton singleton = LazyInitializedSingleton.getInstance();<br><br>        // Access the singleton instance and perform operations<br>        System.out.println(&quot;Singleton instance created: &quot; + singleton);<br><br>        // Demonstrate that multiple calls to getInstance() return the same instance<br>        LazyInitializedSingleton singleton2 = LazyInitializedSingleton.getInstance();<br>        System.out.println(&quot;Singleton instance retrieved again: &quot; + singleton2);<br>        <br>        // Both instances should be equal<br>        System.out.println(&quot;Are both instances equal? &quot; + (singleton == singleton2));<br>    }<br>}</pre><p>Q. Can we use <strong>parameters</strong> with Singleton ?</p><p>A : It’s important to note that while singletons with parameters are possible, they can introduce complexity and potential issues related to thread safety, especially if the parameters are mutable or if there are dependencies between multiple parameters. Careful consideration should be given to the design and usage of such singletons to ensure correctness and maintainability.</p><p><strong>Few examples of Singleton</strong> :</p><ol><li><strong>java.lang.Runtime</strong>: The Runtime class in the java.lang package provides access to the Java Virtual Machine (JVM) runtime environment. It is a singleton class with a private constructor and a static method getRuntime() to obtain the sole instance.</li><li><strong>java.awt.Toolkit</strong>: The Toolkit class in the java.awt package represents an abstract window toolkit. It provides methods for accessing system properties and resources. The Toolkit class follows the Singleton pattern, ensuring that only one instance is created.</li><li><strong>java.util.Calendar</strong>: The Calendar class in the java.util package is used for date and time manipulation in Java. It provides a static method getInstance() to obtain a Calendar instance, which is a Singleton.</li><li>j<strong>ava.util.logging.Logger</strong>: The Logger class in the java.util.logging package provides logging functionality for Java applications. It is typically used to log messages to various output destinations. Logger instances are obtained using static factory methods and follow the Singleton pattern.</li><li><strong>javax.sql.DataSource</strong>: Various implementations of the DataSource interface in the javax.sql package, such as BasicDataSource from Apache Commons DBCP, are often configured as singletons. These instances provide access to a database connection pool.</li></ol><p><strong>Few limitations in Singleton</strong> :</p><p>1. Global State: Singleton introduces a global state, leading to hidden dependencies and coupling between different components. This can make the codebase harder to maintain and understand.</p><p>2. Thread Safety: Ensuring thread safety in Singleton implementations is crucial, but it can be complex and error-prone. Implementing thread-safe Singletons often requires synchronization mechanisms, which can impact performance and introduce subtle bugs.</p><p>3. Testing Difficulty: Singleton dependencies complicate unit testing by introducing global state that affects the behavior of multiple tests. Mocking or stubbing Singletons for testing purposes can be challenging, resulting in less reliable and more brittle tests.</p><p><strong>In conclusion, the Singleton pattern provides a convenient way to ensure that a class has only one instance and offers global access to that instance. While it can be useful for managing global state and resources, it should be used judiciously due to potential drawbacks such as hidden dependencies, testing difficulties, and thread safety concerns. Careful consideration of alternatives and design choices is essential to leverage the benefits of Singleton effectively while avoiding its pitfalls.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=707a60b5bfe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wasted time debugging ! findOne vs getOne in JPA]]></title>
            <link>https://medium.com/@chandanwrites/wasted-time-debugging-findone-vs-getone-in-jpa-b4c4ceb43fb7?source=rss-533a5573e9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4c4ceb43fb7</guid>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Chandan Kumar Barik]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 04:00:57 GMT</pubDate>
            <atom:updated>2023-09-24T04:00:57.217Z</atom:updated>
            <content:encoded><![CDATA[<h3>Wasted time debugging ! findOne vs getOne in JPA</h3><p>It so happened that while I would have used findOne often, somehow in one of the method there was the use of getOne, unsure of how it would have been different from the findOne. <br>I happened to call this method from a new implementation that I was doing and I was getting unintended results, why ? because they work differently.</p><p>When I start debugging the code, I found that the object that I was fetching using the getOne, every attribute inside it was <strong>null. </strong>But then, the one to many relationship that I was building inside it, when I accessed it using a getter and was using in a different method, I saw there were elements inside it. I was certain that something sort of lazy loading was happening.</p><pre><br>private String stringExample;<br><br>@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)<br>@JoinColumn(name = &quot;columnB&quot;)<br>private List&lt;ClassB&gt; classB;</pre><p><strong>getOne</strong> :</p><p>It is mostly used for retrieving a reference (proxy) to an entity without actually loading its attributes from the database until they are accessed. It returns a proxy object that represents the entity, but the actual database query is deferred until you access a property or method that requires data from the entity.</p><p>This method is useful when you want to create associations or relationships with other entities without incurring the overhead of loading all the data for the referenced entity.</p><p>It is not suitable for cases where you need to work with the complete entity object immediately, as it may throw an exception if the entity with the given identifier doesn’t exist in the database. It doesn’t perform an actual query until you access the entity’s data.</p><p><strong>findOne</strong> :</p><p>It is used for fetching an entity from the database with all its attributes immediately. It performs an actual database query and returns the complete entity object, or ‘null’ if the entity with the given identifier doesn’t exist.</p><p>This method is suitable when you need to work with the entity’s attributes immediately or check if an entity with a specific identifier exists in the database.</p><p>Thus, to not wonder why attributes are null while everything seems perfect in your remaining piece of code, there is data in the tables for the record you are trying to fetch, and an attribute with 1-to-many relationship of the object seems to be not null and working fine when you have fetched it through getter method, then you must be cautious of using getOne and findOne.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhlfSUMxhSUFEbRIS-5BKQ.png" /></figure><p>But worry not, the vaugue naming of getOne is now solved by bringing a different method for the same : <strong><em>getRefereneceById</em></strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4c4ceb43fb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 17 Features]]></title>
            <link>https://medium.com/@chandanwrites/java-17-features-a9f921e5dce1?source=rss-533a5573e9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9f921e5dce1</guid>
            <category><![CDATA[java17]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Chandan Kumar Barik]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 06:26:28 GMT</pubDate>
            <atom:updated>2023-04-17T06:26:28.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>Records</h3><p>Data carries classes, those we often term as POJO classes [Plain Old Java Object], and then there are other classes which are functional in nature.</p><p>The characteristics of those data carries class is expected to be :</p><ol><li>Immutable</li><li>Only used for data storage or as carrier</li></ol><p>To set values for the variables and to fetch the data, we are using constructors, getters and setters. The default toString method needs to be overriden in case we wish to print the data of the object without getting some hashed value when we print the object directly. To compare two objects which are having same values in each attributes, they would still be unequal and we would be in need of overriding the equals method as well.</p><p>To avoid all these extra methods, the concept of RECORD was introduced and get rid of all ther boilerplate codes.</p><pre>public record Student(int id, String name, String gender, String contact) {<br><br>}</pre><p>Note :</p><ol><li>default constructor is not there by default in the record and it needs to be explicitly declared.</li></ol><p>2. The values can’t be changed since we don&#39;t have setters here and its immutable.</p><h3>Switch Statement</h3><p>It evolved a lot over a period of time from Java 7 to 17.</p><h4>Java 7 :</h4><p>Only integer can be passed to switch statements :</p><pre>int val =1;<br><br>switch (val) {<br>Case 1 : <br>        System.out.println(&quot;First Option&quot;);<br>        break;<br>Case 2:<br>        System.out.println(&quot;Second Option&quot;);<br>        break;<br>default :<br>        System.out.println(&quot;Option Not There&quot;)<br><br>}<br></pre><h4>Java 8:</h4><p>String and enum can be passed.</p><h4>Java 12:</h4><p>Switch statement transioned to switch express and we can return a value from switch with the use of arrow function, break keyword.</p><p>We can use multiple values in case.</p><pre>switch (day) {<br>            case MONDAY, FRIDAY, SUNDAY -&gt; 6;<br>            case TUESDAY                -&gt; 7;<br>            case THURSDAY, SATURDAY     -&gt; 8;<br>            case WEDNESDAY              -&gt; 9;<br>            default -&gt; throw new IllegalStateException(&quot;Invalid day: &quot; + day);<br>        }</pre><h4>Java 13 :</h4><p><strong>break</strong> keyword in switch was replaced with <strong>yield</strong> keyword.</p><h4>Java 17 :</h4><ol><li>pattern matching : We can match patterns in case. Objects can be passed in case.</li></ol><pre>switch (obj) {<br>            case null     -&gt; System.out.println(&quot;null&quot;);<br>            case String s -&gt; System.out.println(&quot;String&quot;);<br>            case Color c  -&gt; System.out.println(&quot;Color with &quot; + c.values().length + &quot; values&quot;);<br>            case Point p  -&gt; System.out.println(&quot;Record class: &quot; + p.toString());<br>            case int[] ia -&gt; System.out.println(&quot;Array of int values of length&quot; + ia.length);<br>            default       -&gt; System.out.println(&quot;Something else&quot;);<br>        }<br><br>Source : https://docs.oracle.com/en/java/javase/18/language/pattern-matching-switch-expressions-and-statements.html</pre><p>2. guarded pattern :</p><p>Guarded patterns help us to avoid additional if conditions in switch statements. Instead, we can move our conditional statements to the case label.</p><pre>case Triangle t &amp;&amp; t.getArea()&gt;2000 -&gt; System.out.println(&quot;Triangle with area greater than 2000 is detected&quot;);</pre><p>3. null case : null gets handled in the case.</p><h3>Sealed Classes</h3><p>When we want to have a class whose functionalities fall somewhere in between abstract class [ whose methods needs to be implemented ] versus a final class [ which can not be inherited ], Java came up with Sealed Classes.</p><p>Sealed classes allows us to catgorise which classes can extend them.</p><pre>public class SealedClassExample {<br><br>    sealed class finalClassExample permits second,third {<br><br>    }<br><br>    final class second extends finalClassExample {<br><br>    }<br><br>    final class third extends finalClassExample {<br><br>    }<br><br>}</pre><p>Here, the subclasses must be final, sealed or non-sealed.</p><p>Hence, these were the major enhancements that were done in Java 17.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9f921e5dce1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot 3.0]]></title>
            <link>https://medium.com/@chandanwrites/spring-boot-3-0-435bb2cc11ab?source=rss-533a5573e9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/435bb2cc11ab</guid>
            <category><![CDATA[spring-boot-3]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java17]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Chandan Kumar Barik]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 03:54:44 GMT</pubDate>
            <atom:updated>2023-04-13T03:54:44.121Z</atom:updated>
            <content:encoded><![CDATA[<p>We are in 2023 April, and if you have been someone who has worked in projects involving Java And Spring Boot, you would have already worked on Spring Boot 2.0.</p><p>With the release of Spring Boot 3.0, there would be questions arising about what are the new features, should we be moving to 3.0 and how to upgrade to 3.0.</p><h3>Upgrading to 3.0</h3><p>To upgrade to 3.0, any earlier versions of Spring Boot should be first upgraded to 2.7 and then from 2.7 to 3.0.</p><h3><strong>Concept of Record</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*uL3IslDIs9TNsM1NnO5blg.png" /></figure><p>Records were introduced in Java 14, they are immutable data classes. As per documentation, Like an enum, a record is a restricted form of a class. It’s ideal for &quot;plain data carriers,&quot; classes that contain data not meant to be altered and only the most fundamental methods such as constructors and accessors.</p><p><strong>A record aims to eliminate all the boilerplate code needed to set and get the data from the instance.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*YMlXcM43oReHxGVVvVbd0Q.png" /></figure><h3>Spring Boot 3.0 Supports Java 17</h3><p>As a result we were able to add the features related to Java 17 : Records.</p><h3>Jakarta Edition</h3><p>It used Jakarta package instead of earlier Java EE.<br>For example,</p><pre>import jakarta.servlet.http.HttpServletRequest;</pre><p>The project structure will look like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Bm0Hi-7maMp6z0u1VhQb2A.png" /></figure><p>Controller will be :</p><pre>@RestController<br>@RequestMapping(&quot;/studentinfo&quot;)<br>public class StudentController {<br><br>    @Autowired<br>    private StudentService studentService;<br><br>    @PostMapping(&quot;/student/&quot;)<br>    public Student addStudent(@RequestBody Student student) {<br><br>        HttpServletRequest request;<br>        return this.studentService.addStudent(student);<br>    }<br><br>    @GetMapping(&quot;/student/&quot;)<br>    public List&lt;Student&gt; getAllStudents() {<br>        return studentService.getAllStudents();<br>    }<br><br>    @GetMapping(&quot;/student/{id}&quot;)<br>    public Student getStudent(@PathVariable Integer studentId) {<br>        return studentService.getStudent(studentId);<br>    }<br>}</pre><p>Service :</p><pre>@Service<br>public class StudentService {<br><br>    private final List&lt;Student&gt; studentList = new ArrayList&lt;&gt;();<br><br>    public Student addStudent(Student student) {<br><br>        studentList.add(student);<br><br>        return student;<br>    }<br><br>    public List&lt;Student&gt; getAllStudents() {<br>        return studentList;<br>    }<br><br>    public Student getStudent(Integer studentId) {<br>        return studentList.stream().filter(s -&gt; s.id() == studentId).findAny().orElseThrow(() -&gt; new RuntimeException(&quot;Student Not Found for &quot; + studentId));<br>    }<br><br>}</pre><p>Add Few Students :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*dlzyk3yiPKbEoz1jXc_Urw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*JIiidrQata6M1I1SH6FKMg.png" /></figure><p>Get All Students :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*EMqySxgw_etSYBT8b6v-4g.png" /></figure><h3>Problem Detail Feature :</h3><p>It helps to deal with errors specific to Http, i.e., when HTTP status codes are not enough to explain the problems with a HTTP based API.</p><p>Get Student By Id :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*Yo5tyV-r6r1ZTUo_C4GwOA.png" /></figure><p>When we try to get a student by id for the id which doesn’t exist, we shall get the exception. Our exception will be handled using Problem Detail.</p><pre>@RestControllerAdvice<br>public class StudentExceptionHandler {<br><br>    @ExceptionHandler(RuntimeException.class)<br>    public ProblemDetail exceptionHandler(RuntimeException exception) {<br>        var problemDetails = ProblemDetail.forStatusAndDetail(HttpStatusCode.valueOf(404), exception.getMessage());<br>        problemDetails.setTitle(&quot;RunTime Exception - Object Not Found&quot;);<br>        return problemDetails;<br>    }<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*3RKlo2y_gU0DAA3HGbJYcg.png" /></figure><h3>Observability Feature</h3><p>Make changes in the StudentService class to adopt the observability feature :</p><pre>@Service<br>public class StudentService {<br><br>    private final List&lt;Student&gt; studentList = new ArrayList&lt;&gt;();<br><br>    @Autowired<br>    private ObservationRegistry registry;<br><br>    public Student addStudent(Student student) {<br><br>        studentList.add(student);<br><br>        // return student;<br>        return Observation.createNotStarted(&quot;addStudent&quot;, registry).observe(() -&gt; student);<br>    }<br><br>    public List&lt;Student&gt; getAllStudents() {<br>        // return studentList;<br>        return Observation.createNotStarted(&quot;getAllStudents&quot;, registry).observe(() -&gt; studentList);<br>    }<br>...</pre><p>Add below to application.properties</p><pre>management.endpoints.web.exposure.include=*<br>management.endpoints.health.show-details=always<br>spring.mvc.problemdetails.enabled=true</pre><p>On checking the actuator :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mc8VUm9oFAaTVE9chQ-4Rw.png" /></figure><pre>{<br>  &quot;names&quot;: [<br>    &quot;addStudent&quot;,<br>    &quot;addStudent.active&quot;,<br>    &quot;application.ready.time&quot;,<br>    &quot;application.started.time&quot;,<br>    &quot;disk.free&quot;,<br>    &quot;disk.total&quot;,<br>    &quot;executor.active&quot;,<br>    &quot;executor.completed&quot;,<br>    &quot;executor.pool.core&quot;,<br>    &quot;executor.pool.max&quot;,<br>    &quot;executor.pool.size&quot;,<br>    &quot;executor.queue.remaining&quot;,<br>    &quot;executor.queued&quot;,<br>    &quot;http.server.requests&quot;,<br>    &quot;http.server.requests.active&quot;,<br>    &quot;jvm.buffer.count&quot;,<br>    &quot;jvm.buffer.memory.used&quot;,<br>    &quot;jvm.buffer.total.capacity&quot;,<br>    &quot;jvm.classes.loaded&quot;,<br>    &quot;jvm.classes.unloaded&quot;,<br>    &quot;jvm.compilation.time&quot;,<br>    &quot;jvm.gc.live.data.size&quot;,<br>    &quot;jvm.gc.max.data.size&quot;,<br>    &quot;jvm.gc.memory.allocated&quot;,<br>    &quot;jvm.gc.memory.promoted&quot;,<br>    &quot;jvm.gc.overhead&quot;,<br>    &quot;jvm.gc.pause&quot;,<br>    &quot;jvm.info&quot;,<br>    &quot;jvm.memory.committed&quot;,<br>    &quot;jvm.memory.max&quot;,<br>    &quot;jvm.memory.usage.after.gc&quot;,<br>    &quot;jvm.memory.used&quot;,<br>    &quot;jvm.threads.daemon&quot;,<br>    &quot;jvm.threads.live&quot;,<br>    &quot;jvm.threads.peak&quot;,<br>    &quot;jvm.threads.states&quot;,<br>    &quot;logback.events&quot;,<br>    &quot;process.cpu.usage&quot;,<br>    &quot;process.start.time&quot;,<br>    &quot;process.uptime&quot;,<br>    &quot;system.cpu.count&quot;,<br>    &quot;system.cpu.usage&quot;,<br>    &quot;tomcat.sessions.active.current&quot;,<br>    &quot;tomcat.sessions.active.max&quot;,<br>    &quot;tomcat.sessions.alive.max&quot;,<br>    &quot;tomcat.sessions.created&quot;,<br>    &quot;tomcat.sessions.expired&quot;,<br>    &quot;tomcat.sessions.rejected&quot;<br>  ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apKSlAovfoDs816EVmoJ5A.png" /></figure><pre>{<br>  &quot;name&quot;: &quot;addStudent&quot;,<br>  &quot;baseUnit&quot;: &quot;seconds&quot;,<br>  &quot;measurements&quot;: [<br>    {<br>      &quot;statistic&quot;: &quot;COUNT&quot;,<br>      &quot;value&quot;: 2.0<br>    },<br>    {<br>      &quot;statistic&quot;: &quot;TOTAL_TIME&quot;,<br>      &quot;value&quot;: 2.284E-4<br>    },<br>    {<br>      &quot;statistic&quot;: &quot;MAX&quot;,<br>      &quot;value&quot;: 0.0<br>    }<br>  ],<br>  &quot;availableTags&quot;: [<br>    {<br>      &quot;tag&quot;: &quot;error&quot;,<br>      &quot;values&quot;: [<br>        &quot;none&quot;<br>      ]<br>    }<br>  ]<br>}</pre><h3>Spring Native and Graal VM</h3><p>Spring Boot 3.0 supports Graal VM.</p><p>GraalVM is <strong>a high-performance JDK designed to accelerate Java application performance while consuming fewer resources.</strong></p><p>This allows us to move our Spring Boot Application to a Graal Native image, and helps us to have ahead of time processing, thus the application startups faster.</p><p><strong>Ahead-of-time compilation</strong> (<strong>AOT compilation</strong>) is the act of <a href="https://en.wikipedia.org/wiki/Compiler">compiling</a> an (often) higher-level <a href="https://en.wikipedia.org/wiki/Programming_language">programming language</a> into an (often) lower-level language before execution of a program, usually at build-time, to reduce the amount of work needed to be performed at <a href="https://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase)">run time</a>.</p><h3>Http Exchange</h3><p>It is introduced in spring boot 3.0 to consume web services.</p><p>Thus, Spring Boot 3.0 brings the important features of Observability and Native Executables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=435bb2cc11ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AOP In Spring Boot]]></title>
            <link>https://medium.com/@chandanwrites/aop-in-spring-boot-78fe419576a1?source=rss-533a5573e9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/78fe419576a1</guid>
            <category><![CDATA[aop]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Chandan Kumar Barik]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 09:12:32 GMT</pubDate>
            <atom:updated>2023-03-31T09:12:32.979Z</atom:updated>
            <content:encoded><![CDATA[<p>AOP [Aspect Oriented Programming] aims at addressing cross cutting concerns such as loggin, security.</p><p>Our application has different layers like <strong>Web Layer, Business Layer, Data Layer.</strong></p><p>While each layer has a differnt role, there are a few common aspects that apply to all layers are <strong>Logging, Security, validation, caching,</strong> etc. These common aspects are called <strong>cross-cutting concerns.</strong></p><p>Here, we will create a project from scratch and check the impact of AOP in two different APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*k4FJQ6WRGk6M8RKRHFNDfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*B2ASRsPvFxJajTpmd1HYHA.png" /></figure><p>The files to be added as per the below project structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*yaBdXDL_MBKz6o8ky3wRFw.png" /></figure><p>In pom.xml, the dependencies for the AOP needs to be added :</p><pre> <br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-aop&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>The @EnableAspectJAutoProxy annotation needs to be added.</p><pre>@SpringBootApplication<br>@EnableAspectJAutoProxy<br>public class AopImplementationApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(AopImplementationApplication.class, args);<br> }<br><br>}</pre><p>Two APIs will be added to controller :</p><pre>@RestController<br>public class AOPImplentationController {<br><br>    @RequestMapping(value = &quot;/testaop/&quot;, method = RequestMethod.GET)<br>    public String testMethod() {<br><br>        return &quot;Method Called&quot;;<br>    }<br><br>    @RequestMapping(value = &quot;/testaop/method2/&quot;, method = RequestMethod.GET)<br>    public String testMethod2() throws InterruptedException {<br>        Thread.sleep(10090);<br>        return &quot;testMethod2 Called&quot;;<br>    }<br>}</pre><p>Aspect file needs to be created, with below methods, one to log information before the method is called, one to log information after the method is called, and one to check the time taken for method execution.</p><pre>@Aspect<br>@Component<br>public class LogAspect {<br><br>    @Before(&quot;execution(* com.demo.chandan..*.*(..))&quot;)<br>    public void logBeforMethodCall(JoinPoint joinPoint) {<br>        System.out.println(&quot;Method to be called : &quot; + joinPoint.getSignature().getName());<br>    }<br><br>    @After(&quot;execution(* com.demo.chandan..*.*(..))&quot;)<br>    public void logAfterMethodCall(JoinPoint joinPoint) {<br>        System.out.println(&quot;Method Execution Finished : &quot; + joinPoint.getSignature().getName());<br>    }<br><br>    @Around(&quot;execution(* com.demo.chandan..*.*(..))&quot;)<br>    public void findExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {<br>        long startTime = System.currentTimeMillis();<br>        Object result = joinPoint.proceed();<br>        long endTime = System.currentTimeMillis();<br>        long executionTime = endTime - startTime;<br>        System.out.println(joinPoint.getSignature() + &quot; executed in &quot; + executionTime + &quot;ms&quot;);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*g5J5fSPYGJt7oK7Iv-50hQ.png" /><figcaption>We will test the logging by calling the API in postman.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*HHlNA9ek4KBu7NA4pOukdA.png" /></figure><p>To test the time taken for method execution specifically, we will call the second API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*MXHcE8Wek_y89BJwMDR-7A.png" /></figure><p>Hence, using AOP we can address cross cutting concerns by writing the code at one place and observe the changes across application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78fe419576a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Excels in Java for Faster Data Processing And Object Creation]]></title>
            <link>https://medium.com/@chandanwrites/reading-excels-in-java-for-faster-data-processing-and-object-creation-b5f66cdf994b?source=rss-533a5573e9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5f66cdf994b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[import]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[bulk]]></category>
            <dc:creator><![CDATA[Chandan Kumar Barik]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 05:59:25 GMT</pubDate>
            <atom:updated>2023-03-31T06:02:10.002Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello !</p><p>In this blog we will get to learn about the way we can use excels to import data in Java for creating object in bulk. Usually in different applications we might come across scenarios where we need to create objects in large numbers. Under such a scenario, creating objects individually one by one using a UI might be too cumbersome and time consuming.</p><p>Here, we will see an API from scratch which will read some basic data from an excel and push them to Java Objects and return as a response. We will be creating with basic data which can be extended later based on the usecase and operations that needs to be performed on those data.</p><p>Create a new Spring Object using below step :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*_QtiqGgBuCzxySKQri1ISg.png" /></figure><p>Fill the data as per below example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*DVYhyfJwDUhOffMCJlfTkQ.png" /></figure><p>Select Dependencies :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*8HX6ZKLrX2TfOjmGEWq0Tg.png" /></figure><p>We need to create below files and packages after the basic project structure is created :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*UYknZ8E5KFqQNWEc6ad14g.png" /></figure><p>Add below dependencies in pom.xml :</p><pre> <br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.apache.poi&lt;/groupId&gt;<br>   &lt;artifactId&gt;poi&lt;/artifactId&gt;<br>   &lt;version&gt;3.17&lt;/version&gt;<br>  &lt;/dependency&gt;<br>  <br>  <br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.apache.poi&lt;/groupId&gt;<br>   &lt;artifactId&gt;poi-ooxml&lt;/artifactId&gt;<br>   &lt;version&gt;3.17&lt;/version&gt;<br>  &lt;/dependency&gt;</pre><p>Add below code in RestController File :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*XwYbaILc-j4tqkqXYL95aA.png" /></figure><p>Here we will return the list of object that we will be populating after reading the data from Excel. We will be sending the file in the request param.</p><p>The ObjectImprtedBO will be a class we will create where we will populate the data from the excel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*As47ElMYy7AusP7TxU-JnQ.png" /></figure><p>We will create a Service class where we will give the implementation to read the data from excel and then pushing the same to the object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*YrrBgfFMRT5I7tqQ0KJ2Yw.png" /></figure><p>We will run the application and then test the same using postman.</p><p>Excel used is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*NBsSI--PwxGkS5ovwV5eRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*N15GzouZAN1OL00VdEuSkw.png" /><figcaption>Using postman hit the API</figcaption></figure><p>The Response obtained is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*ynxGkL2QNFmxj0HnFfWO3w.png" /></figure><p>Thus, using this simple API to read data from excel we could reduce time taken for object creation. The reading of header names for different columns can be made dynamic by further working on the code implementation and hence can be used to create complex object as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5f66cdf994b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Humans and Nations — Indian Context]]></title>
            <link>https://medium.com/@chandanwrites/humans-and-nations-indian-context-8f0ad1fd6c0?source=rss-533a5573e9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f0ad1fd6c0</guid>
            <category><![CDATA[international-relations]]></category>
            <category><![CDATA[india]]></category>
            <category><![CDATA[diplomacy]]></category>
            <dc:creator><![CDATA[Chandan Kumar Barik]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 08:25:45 GMT</pubDate>
            <atom:updated>2022-12-28T08:29:36.519Z</atom:updated>
            <content:encoded><![CDATA[<h3>Humans and Nations — Indian Context</h3><p>Nations are like the bigger form of Individuals; it has probably got a soul, a personality type [ ideology] and its own way of dealing with everyone else. <br>Remember, “ State is individual writ large”.</p><p>There are many individuals who often keep their self interest aside and come out to help others, regardless of whether those people have been good or bad to them in past, or whether they show any promising character for future relationship in future. We act from our soul. Our inner thought. You know what ? India has got a soul. How so? The way India behaves towards its neighbours despite knowing that they would be helpful less, talk about India-Nepal, India-Bhutan, India-Bangladesh, or India- Sri Lanka. Even when these neighbours much like our everyday neighbours tend to be reckless, sometimes evil and sometimes they get over our head when we become too much caring about them; still we possess a light heart, a soft corner towards them, the feeling that they are part of our own, a different home, a different geography but someone from us. <br>Wouldn’t life have been a little more easy if we cared less ? May be, may be not. We probably have our own self interest when we are nice to others, sometimes out of our heart, let’s say if India was an empathetic character, and sometimes out of knowing where we stand and being realistic.</p><p>If we as humans were like USA, following the path of “No permanent friends and no permanent enemy”, would we have someone to listen to our woes when life turns out bad. May be it works when you are too superior to get affected by others. But still, what if one day you would have become too superior, too powerful and lack the spiritualism to sustain a healthy lifestyle, a selfishness to the point that you would get your work done but be not loved by anyone. Probably realism works in the sphere of International Relations but might not be in an Individuals life.</p><p>We all deserve a friend like Russia, don’t we, even when we know sometimes it puts us in a position of political quagmire where a wrong step would have us slipped. We remember people for their help in past, don’t we. Sometimes that friend turns out to be against your new found girlfriend, acquaintance, whatever… could be a social deadlock.</p><p>And then there are few who sometimes turn rebels when one of our enemy give them something for free. You know who !</p><p>Then their are few who get broke for no reason, and out of brotherhood, or what; like parents; have to give them something to get up on their feet. Quite a few ungrateful people or countries.</p><p>Then there is someone who was like brother once, but behaves like a spoiled son.</p><p>We live somewhere in the middle path ; blending idealism and realism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f0ad1fd6c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Programming Using Spring Webflux]]></title>
            <link>https://medium.com/@chandanwrites/reactive-programming-using-spring-webflux-30aeaa885eb3?source=rss-533a5573e9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/30aeaa885eb3</guid>
            <category><![CDATA[webflux]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Chandan Kumar Barik]]></dc:creator>
            <pubDate>Sun, 13 Mar 2022 16:32:03 GMT</pubDate>
            <atom:updated>2022-03-14T04:21:56.840Z</atom:updated>
            <content:encoded><![CDATA[<p>Software development has evolved a lot over time, from Monolith Applications which are deployed in application servers to Microservices Applications deployed in Cloud Environments facilitating Distributed Systems. Applications with the expectations of minimum response time as possible- in the span of mill seconds, with zero downtime, and automatic scaling and load balancing.</p><p>Talking about building Restful API using Spring Boot, it has it’s own concerns with regard to not being able to support concurrency for higher number of requests and thus we need delve into the concept of Blocking APIs.</p><p>Understanding Blocking And Non Blocking Calls :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*VNkjqjGTbRTENk1L3GSj2g.png" /><figcaption>Thread per Request Model</figcaption></figure><p>In a spring boot project, we can have a tomcat as embedded server. In this traditional REST API call, each of the client calling the application are individual requests to the application. From the thread pool, each request is assigned one thread which will handle the request from start to end. The thread is assigned to the request throughout, and till the request gets its data from the Database and is returned to the client as a response, the thread is reserved for that request. In other words, the thread is blocked for usage by any other request. Thus, the thread per request model won’t scale for today’s application needs.</p><p>With this model, if we have a thread pool of size N, and we want to support concurrency of request more than N, then it won’t become possible, because at any particular moment, at max the application can support only N requests. Even if we can increase the thread pool size but only to certain limit owing to the cost that comes in terms of heap usage per each thread.</p><p>The synchronous nature of doing things acts as a big drawback for the Thread per request model as it gets blocked for any I/O operation that needs to be performed, be it pulling data from DB or calling any external API.</p><p>This Blocking nature becomes a disadvantage to the application as it leads to :</p><ul><li>Application Down Time</li><li>Poor Use of CPU Resource</li></ul><p>The blocking nature of API can be explained using an example from real life. For example, if a person wants to open a Restaurant with 2 waiters and 2 cooks. Here the Restaurant is equivalent to the application, waiters are the threads and cooks are I/O resources doing some I/O operations. When a customer comes and orders for a particular dish, the waiter takes the order, goes to the cook and waits there till the cook 1 has finished the dish. In another table, a new customer comes and orders for dishes to the waiter 2 and now the waiter 2 goes to cook 2 and waits there till the cook finishes the cooking. The customer at table 2 now wishes to order another dish meanwhile after checking the menu but there is no waiter available to take their orders. The waiters are inside talking to the chef and would come back to the table with the food only when the cooking is finished.</p><p>So, if we have many customers to give the order, there is no availability of waiters to take the orders from them. This can be solved, as happens in real world scenario, that the waiter never waits inside while the chef is cooking, instead the waiters takes the order, informs the same to cook and comes back to the table to take orders from other customers. Meanwhile, once the food is ready, it could be any available waiter who can bring the food from the chef to the customer.</p><p><strong>How we are solving this problem ?</strong></p><p>We need to solve the problem by removing the blocking nature of API.</p><p>Available Options in JAVA for asynchronous call :</p><ol><li>Futures [ java 5] — for asynchronous call.</li><li>Completable Future [ JAVA 9 ] — Functional style asynchronous code.</li></ol><p>While Java supports Completable Future for asynchronous call, but the thread is stuck till the entire collection is built when we are dealing with multiple data elements.</p><p><strong>Reactive Programming :</strong></p><ul><li>It is a new programming paradigm</li><li>is both asynchronous and non-blocking in nature</li><li>functional style code</li><li>data flows as event driven system</li><li>support for back pressure on data stream [ when there is possibility of being laden with huge data from the data source, we can seek to accept only certain volume of data, and then subsequently request further data till we need or just cancel the request]</li></ul><p>Thus, Reactive Programming is handy when there is need to support high load which would not be solved by traditional REST API calls in Spring Boot.</p><p>This problem of Spring Boot is solved by Spring Webflux which removes the blocking nature by introducing netty as the embedded server which is non blocking server and Project Reactor library to write non blocking code. Using the event loop model, now the threads would be assigned to a request and while there is a need to wait for any I/O operations to be performed, the thread will be available for taking up other request, thus working on the <strong>Event Loop Model</strong>.</p><p>Event Loop Model : In Reactive Programming, the requests come to the application, gets assigned the Thread 1, and the thread in turn goes to Database to request for data. The Thread achieves this by sending an event to Database and asks to return data and assign the response to any available thread at that time. Meanwhile the current thread would be free and would be available to take other requests.</p><p>The Reactive Streams form the building block of the Reactive Programming. As per Reactive Streams Specifications, they are of four types of Interfaces.</p><ul><li>Publisher</li><li>Subscriber</li><li>Subscription</li><li>Processor</li></ul><p>Publisher is related to data source or any external APIs serving data.</p><p>Subscription acts a link between the application and the data source.</p><p>Subscriber subscribes to the data from the publisher.</p><p>Processor can act as both processor and publisher as it extends both.</p><p>Setting Up of Project :</p><p>Using your favourite IDE, we can build the spring boot starter project. I have used STS.</p><ol><li>Add the basic details about the project.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*JxoaGKEgOsBusYjgApNK2Q.png" /></figure><p>2. Add the “Spring Reactive Web” Dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*q1HEvka8-bhUBvxKdeh2Nw.png" /></figure><p>Flux and Mono are Reactive Types.</p><p><strong>Difference between Flux and Mono :</strong></p><p>A Flux object represents a reactive sequence of 0.. N items in the result, whereas a Mono object represents a single-value or empty (0..1) as the result.</p><h4><strong>Reactive Streams Events :</strong></h4><p>Flux is a publisher.</p><p>The subscriber is always attached the publisher.</p><p>To understand how the event calls happen :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*AgtwfHaUeqX7G1AMd8jiEw.png" /></figure><p>The publisher calls the onSubscribe method to handover the Subscription to the Subscriber. The subscription on received by the subscriber, the subscriber calls request method asking to return all the data available. The publisher sends the data one by one on the “onNext” call and after getting each data as per our implementation the string is printed to console.</p><p>After all the events are sent onComplete() is called.</p><p>Much like the Streams API of JAVA8, we can perform transformation operation on data using Operators in Project Reactor.</p><p>For example, map() operator. Same as Streams API of Java8, here it acts on the reactive streams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*cIuPuUNeTKs-SFrc7aIiKQ.png" /></figure><p>To find the difference between the way the API call works in traditonal REST APIs versus the use of Reactive Programming we will consider both the examples :</p><p><strong>Traditional API calls :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*yr9nyDcWme39UlE92EWSNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*LD-sZdeEICOCg2Ejl0Ryrg.png" /></figure><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ZfUBX2W8xexkUpX_vJmdQ.png" /></figure><p>Here, all the data would be returned at once. Even if to fetch one data would need x amount of time, till then it won’t show the entire result till all the data are populated internally in the collection. For example, if the execution time to fetch just one record is 2 second including all type of internal operations, we won’t see any result till 200seconds has passed for all the records to be provided in response.</p><p>Hence, this is synchronous and blocking in nature.</p><p><strong>Using Reactive Programming </strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*XS-BNtpNYTxeIbvtZkrLTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*5vVkeqMH-hf44zPDtvlWBA.png" /></figure><p>Intermediate Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubqVlJBQ5qa5HWHvLple5A.png" /></figure><p>Final Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-RcXatvm8nZC98FoF_9vA.png" /></figure><p>Here, one by one the result is populated. Thus, we could achieve the results in non blocking way.</p><p>Hence, using Spring Web Flux we can support for handling higher number of requests due to the non blocking nature and also provide results with minimum latency as we don’t have to wait for the entire result to be populated at once.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30aeaa885eb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>