<?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 Miladro on Medium]]></title>
        <description><![CDATA[Stories by Miladro on Medium]]></description>
        <link>https://medium.com/@miladro?source=rss-b15ae49d16b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bJrr5efw1NkZ3-iTLiedQA.jpeg</url>
            <title>Stories by Miladro on Medium</title>
            <link>https://medium.com/@miladro?source=rss-b15ae49d16b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:47:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@miladro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How To Migrate From PHP/Laravel To Java/SpringBoot Quickly]]></title>
            <link>https://medium.com/@miladro/how-to-migrate-from-php-laravel-to-java-springboot-quickly-369f33b22098?source=rss-b15ae49d16b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/369f33b22098</guid>
            <category><![CDATA[migrate]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Miladro]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 20:02:47 GMT</pubDate>
            <atom:updated>2022-06-25T05:53:42.323Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>If You’ve been a php/laravel developer and now you’re going to migrate to Java/SpringBoot this article is specially for you.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*NcDzCihf7hSJ0CMg" /></figure><p>In the past I used to be a php developer and used Laravel as my main using framework. I bet, by any measure, it was the best php framework out there and I believe still it is! Because of being very well-engineered and having big potentials to progress everyday. I enjoyed it.<br>Anyway, now I’m a Java Developer who has been using Java and SpringBoot for a few years.<br>My main focus in this article is to help you to migrate and get fluent as quick as possible.</p><h4>Agenda</h4><ul><li>List of major laravel components</li><li>Introduction to SpringBoot</li><li>Laravel equivalent components in SpringBoot</li><li>Building a simple REST app with SpringBoot</li><li>Conclusion</li></ul><h3>List of major laravel components</h3><p>First of all we should list major components and features of Laravel and then find their equivalents in SpringBoot.</p><p>List of main laravel components and features:</p><ul><li>DI (Dependency Injection)</li><li>Controllers</li><li>ORM and database</li><li>Validations</li><li>Exception Handling</li><li>Configurations</li></ul><h3>What is SpringBoot?</h3><p>SpringBoot is nothing but a lightweight as being said “Opinionated view” of it’s big parent the “Spring Framework”. It means, it collects the components of the spring framework and other libraries, configures and puts them together in a special way. Believe me, doing this by yourself is a “pain in the but”! and because of that everyone would rather use SpringBoot instead of pure Spring Framework.<br>SpringBoot doesn’t have a special place for everything, instead gives you freedom to design your own application architecture.<br>Also it “favours convention over configuration”.</p><h3>Laravel equivalent components in SpringBoot</h3><p>Before we jump to learn equivalent components in SpringBoot let me introduce you “Annotations”.<br>Annotations are very common in Java ecosystem. They are used to “decorate” methods and classes in a very nice and clean way. They increase code readability and decrease complexity.<br>Annotation could be used at both runtime and compiletime. You may want to decorate a class or a method with annotation to add functionality in either runtime or compiletime.<br>SpringBoot comes with many of them for different purposes. For example you put @Controller annotation on a class and SpringBoot’s runtime interprets it and knows it’s a controller.</p><h4>DI (Dependency Injection) in SprinBoot</h4><p>The core component of the SpringBoot is DI. Other things are just independent components and libraries from elsewhere which are bundled into the framework.<br>In laravel if you’re going to inject a dependency it should’ve been registered as a service provider. If it’s a common dependency like a “FormRequest” object they are registered in the framework already, but if it’s a custom dependency/driver you should register it as service provider in providers directory. (<a href="https://laravel.com/docs/9.x/providers">full details here</a>)<br>Spring boot provide you several stereotype annotations like: @Controller @Service @Repository @Component (these are class level). They are just beans but with different names. you could use @Bean annotation for define custom components. <br>At the application start-up spring scans all classes annotated with these annotation and inject them into the IOC container. There’s no need for registering a class as a service provider and customly adding it to providers array! That’s why we call it “convention over configuration”.</p><h4>Controllers</h4><p>We could have both kind of Rest and MVC controllers in spring boot with proper annotations. Unlike laravel we don’t have to configure our routes in a specific different place. We could just use @RequestMapping annotation (and it’s subsets) for a controller method and have fun :)</p><h4>ORM and database</h4><p>Laravel comes with <a href="https://laravel.com/docs/5.0/eloquent">Eloquent ORM</a> in default. In spring boot you can add spring-data (maven/gradle) dependency to your project and spring-boot detects that and automatically configure all the things for you. You just need to add some property configurations for database name, port and etc.<br>Spring-data is an abstraction layer that make you able to work with different implementation and drivers like Hibrnate ORM, MongoDB driver, etc. with the same API. You just need to make a @Repository class/interface and in a case that you need more customized special queries, that’s available too.</p><h4>Validations</h4><p>Validations in spring-boot are handled easily, again with annotations!<br>With request-mapping feature you tell the spring map request objects to specified classes. And in those classes, which we call DTO (Data Transfer Object) class, we use validation annotations on each field to define validation rules.</p><h4>Exception Handling</h4><p>Another big part of SpringBoot that it brings easily is “Spring AOP”. AOP means Aspect Oriented Programming. I don’t want to get into details, you could read more about it later. But in brief it’s OOP complementer. With it you define what must happen before/during/after a specific point of the program (specifically methods).<br>In laravel all the logic for handling all exceptions must be written in register() method of App\Exceptions\Handler class. Again, specific place, configurational approach!<br>But in SpringBoot you could write an aspect class annotated with @ControllerAdvice and handle different exceptions with methods annotated with @ExceptionHandler annotation. (You write the logic of handling in the body of the method).</p><h4>Configuration</h4><p>In laravel you have .env file and would assign values to properties and use those properties in your application. You would use your properties values by calling env() global method inside your application logic. SpringBoot is very similar to this. You have application.properties file and you could inject the value of those properties into the fields of classes with @value(“nam-of-the-property”) annotation.<br>You can also utilize @Configuration with configuration classes and map a whole property namespace to a class.</p><h3>Building a simple REST app with SpringBoot</h3><p>Enough said! Let’s get get our hands dirty.<br>In the following steps we will create a REST API for a resource named “Post”.</p><ol><li>Add maven dependencies</li><li>Create project structure</li><li>Create a controller</li><li>Create a service</li><li>Create a repository</li><li>Test an endpoint</li></ol><figure><img alt="Get your hands dirty" src="https://cdn-images-1.medium.com/max/800/0*ZCS9r-PEEpGSWgcC" /><figcaption>Get your hands dirty with spring boot</figcaption></figure><h4>Add maven dependencies</h4><p>Maven is nothing but a package manger like composer for Java. <br>We will use <a href="https://start.spring.io/">spring initializr </a>in order to pack our necessary compatible dependencies. But you can also create a maven project, then add dependencies customly (in that case you have to figure out version compatibality by yourself). <br>I will add this 3 necessary dependencies by spring initializr:</p><ul><li>spring-boot-starter-web (Spring Web)</li><li>Lombok (A library to reduce boilerplate code by generating getters/setters/etc.)</li><li>Spring Data MongoDB</li></ul><p>Also I will add MapStruct library customly, which helps us at mapping/transforming objects. Mappers are similar to “<a href="https://laravel.com/docs/9.x/eloquent-resources#introduction">API Resources</a>” in laravel.<br>Other dependencies that you’re gonna see in “pom.xml” are optional. pom.xml file is like composer.json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*SM0hteFjDKOoOR6SurChsg.png" /><figcaption>spring boot required dependencies</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLkzggnAIIYl_z0pRGr4CQ.png" /><figcaption>MapStruct pom</figcaption></figure><h4>Project structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*UQtlDZt68RqsnLxGX6SvIg.png" /></figure><p>I think everything is clear so I’m not going to describe every part. api is for “web layer” (controllers and etc.) , dal for “data access layer” (repositories, database models (Entities), etc.) and service is the place that we would write our business logic in service classes.</p><h4>Create a Controller</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vnv3ALTClefRGWlHOSEFJg.png" /></figure><p>You see? there is no need for defining all routes in a different place. Also validation could be enabled by @Validated annotation on a DTO object. I think this is nice and clean :)</p><h4>Create a service</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7RVE4DkbgQMBEivKzI9-Q.png" /></figure><p>SimplePostService is an implementation of PostService interface. SpringBoot detects that and will inject this implementation.<br>The business logic is simple, create a post, generate and set it’s ID, save it to the DB.</p><h4>Create a repository</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uVETjknTJoxzw1fdld1IzA.png" /></figure><p>This is The post repository. There’s no need to write a actual query, database instructions or any specific logic. You just define a few methods by a specific convention (don’t worry your IDE will help you) and spring data takes care of that by generating implementation of the interface. For other complicated tasks you can write your own implementations.</p><h4>Test an endpoint</h4><p>We will test <em>create post</em> rest endpoint using postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNqeLyl2B71kQLYYjawxiw.png" /></figure><p>It’s Done. Our first rest spring-boot app works.<br>All other codes are <a href="https://github.com/miladro1/simple-spring-boot-rest">here</a>. Check it out and have fun :)</p><h3>Conclusion</h3><p>SpringBoot and Laravel are both very good quality frameworks in their own ecosystem. Believe me I’m an idealist in the case of choosing tools :) If you’re going to migrate to Java, spring boot is a great choice.<br>One of the best things about spring boot, comparing with laravel, is the <strong>freedom and the flexibility</strong> that gives you. It lets you design and architect your app however you want. However, This could be both and advantage or disadvantage for different people.<br>Another good thing about spring boot is the “<strong>convention over configuration</strong>” that it provides, with the help of annotations and other things.<br>Not only it <strong>packs and configures the best toolset for you</strong>, but also it is <strong>very compatible with so many tools and libraries</strong>. <br>Being <strong>cloud native</strong> is also a very important advantage about spring boot to consider.</p><p>OK. we’re done. I hope you like it and I would be happy if you follow me on medium and <a href="https://github.com/miladro1/spring-boot-simple-rest">give me a star</a> on github :) That’s motivates me for producing more good quality tuts.<br>Also if you have any question please comment it out.</p><h4>Thank you.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=369f33b22098" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Interview Question: How Do You Override The equals Method?]]></title>
            <link>https://medium.com/@miladro/java-interview-question-how-do-you-override-the-equals-method-d3983f12186b?source=rss-b15ae49d16b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3983f12186b</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Miladro]]></dc:creator>
            <pubDate>Sat, 12 Feb 2022 22:49:32 GMT</pubDate>
            <atom:updated>2022-02-24T15:38:44.595Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auSpABfLTHNHy5MFnTvKMg.jpeg" /></figure><p>This is one of the common Java interview questions and may seems easy, but that’s not true! If you don’t aware to implement <em>equals</em> method properly, it could easily ruin your whole application and provide unexpected result. It also makes debugging very difficult.</p><p>Generally it’s good to override the “equals” method when the class has these criteria:</p><ul><li>It’s a <em>Value Class</em>.</li><li><em>Logical Equality </em>is needed.</li><li>A superclass hasn’t overridden equals method.</li></ul><p>So when the above criteria are met, the question is:</p><h4>How should we implement/override the equals method?</h4><p>According to <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiD9JKKo_r1AhUUrqQKHUIOA44QFnoECAUQAQ&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FJoshua_Bloch&amp;usg=AOvVaw1EdgP_KGcr1W_ikwn7686X">Joshua Bloch</a> recommendations (referred as <em>General Contract</em>) the equals method implementation must have these characteristics:</p><ul><li><strong>Non-nullity</strong>: every instance must not be equal to null value (x.equals(null) must return false)</li><li><strong>Reflexive</strong>: every instance must be equal to itself (x.equals(x) must return true).</li><li><strong>Symmetric</strong>: the returning boolean value of x.equals(y) and y.equals(x) must be exactly the same.</li><li><strong>Transitive</strong>: if the returning value of x.equals(y) and y.equals(z) are identical, then the returning value of x.equals(z) must be the same as two previous call (in other words: if x is equal to y, and y is equal to z, then x must be equal to z, too).</li><li><strong>Consistency</strong>: multiple calls to equals method (for example x.equals(y)) must always return the same result.</li></ul><p><em>[Joshua Bloch — Effective Java — Item 10]</em></p><p>With all that in mind, we write a sample value class (named Person) with a TDD approach. One shot, two target :) 1. implementing a right <em>equals</em> method. 2. learning TDD.</p><p>Briefly TDD is about <strong><em>Test-First </em></strong>and <strong><em>Red, Green, Refactor</em></strong> pattern which helps us to write robust and reliable code, very much. Also codes written with TDD approach could be much cleaner and easier to read, because it enforce you to design the API first (not implementation!) and look at the code in the API client’s eyes. These are the steps that should be taken in TDD:</p><ol><li><strong>Write the test</strong>, run it, and get <strong>RED</strong> (if you get green at the first steps perhaps you are lucky or doing something wrong 😄)</li><li><strong>Write the code</strong> with the minimum functionality to satisfy the test, run the test, and get <strong>GREEN</strong>.</li><li><strong>Refactor: </strong>if everything is fine you can now refactor the code for the optimization or cleaning code purposes.</li></ol><p>This cycle could be executed over and over (whenever a new change is required and etc.)</p><p>SpringBoot is my favorite framework that has good packages for test in it and autoconfigures them, which makes the work of testing easy and delightful. So I create a brand new project by spring initiallizer with minimum starter packages including spring-boot-starter and JUnit.</p><h4><strong>Testing Reflexivity</strong>:</h4><pre>package com.miladro.overridingequalmethodtut;<br><br>import org.junit.jupiter.api.Test;<br>import org.junit.jupiter.api.extension.ExtendWith;<br>import org.mockito.junit.jupiter.MockitoExtension;<br><br>import java.util.Random;<br><br>import static org.junit.jupiter.api.Assertions.<em>assertEquals</em>;<br>import static org.junit.jupiter.api.Assertions.<em>assertTrue</em>;<br><br>@ExtendWith(MockitoExtension.class)<br>public class PersonEqualMethodUnitTest {<br><br> @Test<br> public void TestReflexivity_GivenAPersonObjectWithOverriddenEqualsMethod_WhenCallEqualsMethodWithItselfAsTheArgument_ThenTrueShouldBeReturned() {<br> //Given<br> Person person = new Person();<br> person.setFirstName(&quot;John&quot;);<br> person.setFirstName(&quot;Doe&quot;);<br> person.setAge(20);<br><br> //When<br> boolean result = person.equals(person);<br><br> //Then<br> <em>assertTrue</em>(result);<br> }<br>}</pre><p>The test simply create a Person object (class doesn’t exist yet!), calls the equals method with itself as the argument and makes an assertion for returning result to be true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ymp7qZnhcuuc_ZSilBIYsg.png" /></figure><p>Which it fails correctly and we’ll get RED.</p><p>We create Person class, override equals method on it with minimum functionality required and once again run our test case. this time we should get green.</p><pre>package com.miladro.overridingequalmethodtut;<br><br>import lombok.Data;<br><br>@Data<br>public class Person {<br>    private String firstName;<br>    private String lastName;<br>    private int age;<br><br>    @Override<br>    public boolean equals(Object o) {<br>        Person person = (Person) o;<br>        // ensures Reflexivity<br>        return this == person;<br>    }<br>}</pre><p>Casting passed-in parameter and simply comparing it with actual current object by “==” operator, will ensure the Reflexivity for us and would pass our testcase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*Kk8Uzk429TTpxNZnu2oXSQ.png" /></figure><h4>Testing Symmetricity:</h4><p>Once again we write a test with [RED, GREEN, REFACTOR] pattern like previous test-case, this time for testing symmetricity.</p><pre>@Test<br>public void TestSymmetricity_GivenTwoEquivalentPersonObjectsWithOverriddenEqualsMethod_WhenCallEqualsMethodOnFirstObjectWithSecondObjectAsArgumentAndViseVersa_ThenTheReturningResultShouldBeTrue() {<br>    //Given<br>    Person person1 = new Person();<br>    person1.setFirstName(&quot;John&quot;);<br>    person1.setLastName(&quot;Doe&quot;);<br>    person1.setAge(20);<br><br>    Person person2 = new Person();<br>    person2.setFirstName(&quot;John&quot;);<br>    person2.setLastName(&quot;Doe&quot;);<br>    person2.setAge(20);<br><br>    //When<br>    boolean firstComparison = person1.equals(person2);<br>    boolean secondComparison = person2.equals(person1);<br><br>    //Then<br>    <em>assertTrue</em>(firstComparison);<br>    <em>assertTrue</em>(secondComparison);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usUfEGh0LvtpvTntksMSdQ.png" /><figcaption>Getting RED for testing symmetricity test-case</figcaption></figure><p>We get RED, so we add symmetricity functionality to our equals method to get GREEN.</p><pre>@Override<br>public boolean equals(Object o) {<br>    Person person = (Person) o;<br>    //Reflexivity<br>    if (this == person)<br>     return true;<br><br>    //Symmetricity<br>    return person.getFirstName().equals(this.getFirstName())<br>            &amp;&amp; person.getLastName().equals(this.getLastName())<br>            &amp;&amp; person.getAge() == this.getAge();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*Fuc7sTHHG8PqGR5humldOg.png" /><figcaption>Getting GREEN for symmetricity test</figcaption></figure><p>For refactor step we could remove if section and add it to return section:</p><pre>@Override<br>public boolean equals(Object o) {<br>    Person person = (Person) o;<br>    //Reflexivity AND Symmetricity<br>    return (this == person) ||<br>            (person.getFirstName().equals(this.getFirstName())<br>            &amp;&amp; person.getLastName().equals(this.getLastName())<br>            &amp;&amp; person.getAge() == this.getAge());<br>}</pre><h4>Testing Transitivity:</h4><pre>@Test<br>public void TestTransitivity_GivenThreeEquivalentPersonObjectsWithOverriddenEqualsMethod_WhenFirstEqualsSecondAndSecondEqualsThird_ThenFirstShouldBeEqualToThirdAlso() {<br>    //Given<br>    Person person1 = new Person();<br>    person1.setFirstName(&quot;John&quot;);<br>    person1.setLastName(&quot;Doe&quot;);<br>    person1.setAge(20);<br><br>    Person person2 = new Person();<br>    person2.setFirstName(&quot;John&quot;);<br>    person2.setLastName(&quot;Doe&quot;);<br>    person2.setAge(20);<br><br>    Person person3 = new Person();<br>    person3.setFirstName(&quot;John&quot;);<br>    person3.setLastName(&quot;Doe&quot;);<br>    person3.setAge(20);<br><br>    //When<br>    boolean firstEqualsSecond = person1.equals(person2);<br>    boolean secondEqualsThird = person2.equals(person3);<br>    <em>assertTrue</em>(firstEqualsSecond);<br>    <em>assertTrue</em>(secondEqualsThird);<br><br>    //Then<br>    boolean firstEqualsThird = person1.equals(person3);<br>    <em>assertTrue</em>(firstEqualsThird);<br>}</pre><p>Current code supports transitivity also and we get GREEN. So there’s no need to repeat the cycle for this test-case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*0X_TwMbKBQdqliw48u708Q.png" /></figure><h4>Testing Consistency:</h4><p>For Testing consistency we could design our test-case in a way that it calls the equals method multiple times with given random number.</p><pre>@Test<br>public void TestConsistency_GivenMultiplePersonObjectsWithOverriddenEqualsMethod_WhenCompareThemUsingEqualsMethodMultipleTimes_ThenTheReturningResultShouldBeTheSameAllTheTime() {<br>    //Given<br>    Person person1 = new Person();<br>    person1.setFirstName(&quot;John&quot;);<br>    person1.setLastName(&quot;Doe&quot;);<br>    person1.setAge(20);<br><br>    Person person2 = new Person();<br>    person2.setFirstName(&quot;John&quot;);<br>    person2.setLastName(&quot;Doe&quot;);<br>    person2.setAge(20);<br><br>    //When<br>    int trueResultCounter = 0;<br>    Random random = new Random(); // or new Random(someSeed);<br>    int counter = random.nextInt(500);<br>    for (int i = 1; i &lt;= counter; i++) {<br>        if (person1.equals(person2))<br>            trueResultCounter++;<br>    }<br><br>    //Then<br>    <em>assertEquals</em>(trueResultCounter, counter);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*PQ4dIUEnmfObvC2oYNFU1g.png" /></figure><p>Once again our test passes successfully without needing for any change.</p><h4>Testing Non-Nullity:</h4><pre>@Test<br>public void TestNonNullity_GivenAPersonObjectWithOverriddenEqualsMethod_WhenCompareItToNullValueUsingEqualsMethodMultipleTimes_ThenFalseShouldBeReturned() {<br>    //Given<br>    Person person1 = new Person();<br>    person1.setFirstName(&quot;John&quot;);<br>    person1.setLastName(&quot;Doe&quot;);<br>    person1.setAge(20);<br><br>    //When<br>    boolean result = person1.equals(null);<br><br>    //Then<br>    <em>assertEquals</em>(false, result);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blCQygvmK5Cmozyj9qa2ww.png" /><figcaption>Getting RED for non-nullity test</figcaption></figure><p>Non-nullity test fails so we change the code and add non-nullity to functionality to get green:</p><pre>@Override<br>public boolean equals(Object o) {<br>    if (! (o instanceof Person))<br>        return false;<br>    Person person = (Person) o;<br>    //Reflexivity AND Symmetricity<br>    return (this == person) ||<br>            (person.getFirstName().equals(this.getFirstName())<br>            &amp;&amp; person.getLastName().equals(this.getLastName())<br>            &amp;&amp; person.getAge() == this.getAge());<br>}</pre><p>We get GREEN and there’s no need for a refactoring at this point. So our unit is ready for deploy and has all required criteria. Done :)</p><h3>Conclusion:</h3><p>Overriding <em>equals </em>method could be tricky and if you don’t adhere to the general contract and implement it wrongly, it could affect your whole application and leads to getting unexpected results and behaviors. Also debugging and finding the problem on that situation would be very hard and challenging. <br>There are useful tools and libs out there which helps you with this problem, but whenever you find yourself you have to implement the method manually pay an extra attention to override it correctly and adhere to the contracts strongly.</p><p>Also good to mention that TDD and Unit-Testing may seems difficult and time-consuming at first, but once you get used to it, it becomes easy and very helpful. It’s a good practice to stick with it for your projects and development processes, which guarantees more robustness and less bugs.</p><p>Here’s all the code on <a href="https://github.com/miladro1/java-equals-method-tut">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3983f12186b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interview question: How You Handle Thread Safety In Spring Boot?]]></title>
            <link>https://medium.com/@miladro/interview-question-how-you-handle-thread-safety-in-spring-boot-f8c8d3aecbee?source=rss-b15ae49d16b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8c8d3aecbee</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-bean]]></category>
            <category><![CDATA[thread-safety]]></category>
            <dc:creator><![CDATA[Miladro]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 01:30:08 GMT</pubDate>
            <atom:updated>2025-08-13T05:53:47.782Z</atom:updated>
            <content:encoded><![CDATA[<h3>Interview question: How Do You Handle Thread Safety In Spring Boot?</h3><p>Recently in an interview the technical interviewer asked me an interesting question:</p><blockquote><strong>Are Spring Beans Thread Safe?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RaLmrFmoJ4xqbq05.jpg" /></figure><p>Based on my experience and my natural expectations from the framework I answered at that moment with: “<em>Yes, they are.</em>” which was both a right and wrong answer at the same time :)<br>After the interview I did some research and wrote some tests to experiment my knowledge about the framework and now I want to share the result with you.</p><p>Before I start, I should mention thread safety in multi-threaded environments depends on many factors including:</p><ul><li>does objects that we use in multiple simultaneous threads <strong>hold state</strong>?</li><li>does the specific operation or the method we call on the object change internal state of it?</li><li>is the object immutable? (immutable ain’t necessary stateless)</li><li>etc…</li></ul><p>and based on these questions thread safety could be achieved by different approaches each of them has their own pros and cons.</p><p>As you may already know spring beans can have one these four scopes:</p><ul><li>Singleton</li><li>Prototype</li><li>Session</li><li>Request</li></ul><p>Last two are specific to web applications which are managed by WebAwareApplicationContext. <br>Singletons and also their dependencies (even prototypes) are eagerly created and injected at the application startup and long lived till application stop. The word singleton doesn’t have anything to do with the famous “Singleton Design Pattern”. They are not necessarily stateless or immutable either. <br>Prototypes are injected on demands, for example every time we call a method on a prototype bean a new one will be instantiated and injected to the associated object.<br>Lifecycle of session and request beans, as their name suggest, are bound to the lifecycle of a user session or a HTTP request.</p><h4>How We Achieve Thread Safety In Spring Boot?</h4><p>The default front controller (web server) for spring boot web application is Servlet which it creates a new separate thread for every http request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*psu4JlDVVbihlhMPWOz--Q.png" /><figcaption>Spring MVC Context Hierarchy</figcaption></figure><p>Servlet then delegates the control flow to the lower layers beginning from controller layer. Typically none of controllers, services and repositories need to hold state and we leave them with default spring-boot bean scope which is singleton. So if we say we are always working with singletons and we design them stateless and ensure that none of the methods changes the internal state of them, we could be assured that our beans are thread safe. <br>So let’s examine it with some tests:</p><p>To demonstrate thread safety with singletons I create UserService class which simply adds a user to the DB and holds the number of added users within itself (this doesn’t make sense but is just for simulation).</p><pre>@Service<br>public class UserService {<br>    // holding users count in service class doesn&#39;t make sense but it&#39;s just for demonstration :)<br>    public int numberOfCreatedUsers = 0;<br><br>    public int addUser(UserDto userDto) {<br>        UserEntity userEntity = new UserEntity();<br>        userEntity.setUsername(userDto.getUsername());<br>        userEntity.setPassword(userDto.getPassword());<br>        saveUserToDB(userEntity);<br>        return numberOfCreatedUsers;<br>    }<br><br>    private void saveUserToDB(UserEntity userEntity) {<br>        numberOfCreatedUsers++;<br>        System.<em>out</em>.println(&quot;Thread &quot; Thread.<em>currentThread</em>().getName() + &quot;: user saved to db&quot;);<br>    }<br>}</pre><p>Then I create a rest controller for expose the API and test the API with two separate parallel thread (I’ll write a whole another topic about unit and integration test with spring boot later).</p><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br>    private final UserService userService;<br><br>    public UserController(UserService userService) {<br>        this.userService = userService;<br>    }<br><br>    @PostMapping(&quot;/create&quot;)<br>    public int addUser(@RequestBody UserDto userDto) {<br>        return userService.addUser(userDto);<br>    }<br>}</pre><p>The test simply sends two http requests in parallel with different parameters and makes an assertion of the number of created users should be <strong>2</strong>.</p><pre>@SpringBootTest(classes = ThreadSafetyApplication.class,<br>      webEnvironment = SpringBootTest.WebEnvironment.<em>RANDOM_PORT</em>)<br>class ThreadSafetyApplicationTests {<br><br>   @LocalServerPort<br>   int randomServerPort;<br><br>   @Autowired<br>   private UserService userService;<br><br>   @Test<br>   @SneakyThrows<br>   void testSingleton() {<br>      final String baseUrl = &quot;http://localhost:&quot;+randomServerPort+&quot;/users/create&quot;;<br>      URI url = new URI(baseUrl);<br>      UserDto user1 = new UserDto(&quot;user1&quot;, &quot;123&quot;);<br>      UserDto user2 = new UserDto(&quot;user2&quot;, &quot;456&quot;);<br><br>      HttpHeaders headers = new HttpHeaders();<br>      headers.set(&quot;X-COM-PERSIST&quot;, &quot;true&quot;);<br><br>      HttpEntity&lt;UserDto&gt; request1 = new HttpEntity&lt;&gt;(user1, headers);<br>      HttpEntity&lt;UserDto&gt; request2 = new HttpEntity&lt;&gt;(user2, headers);<br><br>      Thread thread1 = new Thread(new PostRequestTask&lt;&gt;(url, request1));<br>      Thread thread2 = new Thread(new PostRequestTask&lt;&gt;(url, request2));<br>      thread1.start();<br>      thread2.start();<br>      thread1.join();<br>      thread2.join();<br><br>      System.<em>out</em>.println(&quot;number of users created: &quot; + userService.numberOfCreatedUsers);<br><br>      <em>assertEquals</em>(2, userService.numberOfCreatedUsers,<br>            &quot;number of users created: &quot; + userService.numberOfCreatedUsers);<br>   }<br>}</pre><p>Which successfully fails :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfAmnjEXzzBl6IPeEVEZEA.png" /><figcaption>Test stateful singleton bean</figcaption></figure><p>Notice: we assume that threads execute at the exact same time, but sometimes this doesn’t happens and test unsuccessfully passes! But the point is: <em>making singletons stateful is not a good choice, but if we do that we should guarantee race condition wouldn’t happen.</em> The simplest way of doing that could be synchronization. For that purpose we make saveUserToDb() method sync and the race condition problem is solved in here. But, again, this is not a right choice, even is an anti-pattern. Me, myself never make singletons stateful.</p><pre>@SneakyThrows<br>void testSingletonWithSync() {<br>   final String baseUrl = &quot;http://localhost:&quot;+randomServerPort+&quot;/users/create-sync&quot;;<br>   URI url = new URI(baseUrl);<br>   UserDto user1 = new UserDto(&quot;user1&quot;, &quot;123&quot;);<br>   UserDto user2 = new UserDto(&quot;user2&quot;, &quot;456&quot;);<br><br>   HttpHeaders headers = new HttpHeaders();<br>   headers.set(&quot;X-COM-PERSIST&quot;, &quot;true&quot;);<br><br>   HttpEntity&lt;UserDto&gt; request1 = new HttpEntity&lt;&gt;(user1, headers);<br>   HttpEntity&lt;UserDto&gt; request2 = new HttpEntity&lt;&gt;(user2, headers);<br><br>   Thread thread1 = new Thread(new PostRequestTask&lt;&gt;(url, request1));<br>   Thread thread2 = new Thread(new PostRequestTask&lt;&gt;(url, request2));<br>   thread1.start();<br>   thread2.start();<br>   thread1.join();<br>   thread2.join();<br><br>   System.<em>out</em>.println(&quot;number of users created: &quot; + userService.numberOfCreatedUsers);<br><br>   <em>assertEquals</em>(2, userService.numberOfCreatedUsers,<br>         &quot;number of users created: &quot; + userService.numberOfCreatedUsers);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gztEof9pPiGrd4nEE7F6Vg.png" /></figure><h4>With prototype, request and session scoped beans we have completely a different story.</h4><p>Let’s assume that we have a purchase service and with every purchase we create an event and send it to a message broker to be used by other services like Acounting, Inventory, Messaging, etc. So with every purchase we create a ProductPurchasedEvent object which holds all necessary data about the purchase and we fire/trigger it. Purchases may be similar which means we might have duplicate repetitive data but even in spite of this condition they are unique on their own. So we should have an event Id to ensure the uniqueness. This scenario may sound a good candidate for using prototype beans.<br>With All that in mind lets write the code and test it:</p><p>PurchaseController:</p><pre>@RestController<br>@RequestMapping(&quot;/purchase&quot;)<br>public class PurchaseController {<br>    private final PurchaseService purchaseService;<br><br>    public PurchaseController(PurchaseService purchaseService) {<br>        this.purchaseService = purchaseService;<br>    }<br><br>    @PostMapping<br>    public boolean purchase(@RequestBody PurchaseProductDto dto) {<br>        return purchaseService.purchase(dto);<br>    }<br>}</pre><p>PurchaseService (singleton):</p><pre>@Service<br>public class PurchaseService {<br>    private ProductPurchasedEvent productPurchasedEvent;<br><br>    @Autowired<br>    public PurchaseService(ProductPurchasedEvent productPurchasedEvent) {<br>        this.productPurchasedEvent = productPurchasedEvent;<br>    }<br><br>    public boolean purchase(PurchaseProductDto dto) {<br>        System.<em>out</em>.println(&quot;Thread: &quot; + Thread.<em>currentThread</em>().getName() + &quot;product: &quot; + dto.getProduct() + &quot; purchased successfully&quot;);<br>        productPurchasedEvent.setProduct(dto.getProduct());<br>        productPurchasedEvent.setBuyer(dto.getBuyer());<br>        return productPurchasedEvent.fire();<br>    }<br>}</pre><p>ProductPurchasedEvent (prototype):</p><pre>@Data<br>@Component<br>@Scope(value = ConfigurableBeanFactory.<em>SCOPE_PROTOTYPE</em>)<br>public class ProductPurchasedEvent {<br>    private String product;<br>    private String buyer;<br>    private String eventId;<br><br>    ProductPurchasedEvent() {<br>        this.eventId = RandomStringUtils.<em>randomAlphanumeric</em>(10);<br>        MessageBroker.<em>eventsCount</em>.incrementAndGet();<br>        MessageBroker.<em>createdEventsIdList</em>.add(eventId);<br>    }<br><br>    public boolean fire() {<br>        String message = buyer + &quot; purchased &quot; + product;<br>        System.<em>out</em>.println(&quot;fire method called _ Thread : &quot; + Thread.<em>currentThread</em>().getName() + &quot; &quot; + message + &quot; eventId: &quot; + eventId);<br>        MessageBroker.<em>messages</em>.add(new Message(eventId, message));<br>        return true;<br>    }<br>}</pre><p>MessageBroker class which simulate a message broker:</p><pre>public class MessageBroker {<br>    public static final AtomicInteger <em>eventsCount </em>= new AtomicInteger(0);<br>    public static final List&lt;String&gt; <em>createdEventsIdList </em>= Collections.<em>synchronizedList</em>(new ArrayList&lt;&gt;());<br>    public static List&lt;Message&gt; <em>messages </em>= Collections.<em>synchronizedList</em>(new ArrayList&lt;&gt;());<br>}</pre><p>Message class:</p><pre>@Data<br>public class Message {<br>    private final String eventId;<br>    private final String content;<br>}</pre><p>Our expectations is when we send two http request and make two purchases at the same time we should have two different instances of ProductPruchasedEvent and two expected messages delivered in message broker. We could examine it with making two assertions:</p><ol><li>eventsCount should be 2</li><li>two expected messages with unique eventId should exist in messages list.</li></ol><pre>@Test<br>@SneakyThrows<br>void testDefaultBehaviourOfPrototypeWithSingleton() {<br>   final String baseUrl = &quot;http://localhost:&quot;+randomServerPort+&quot;/purchase&quot;;<br>   URI url = new URI(baseUrl);<br>   PurchaseProductDto purchaseProductDto1 = new PurchaseProductDto(&quot;book1&quot;, &quot;user1&quot;);<br>   PurchaseProductDto purchaseProductDto2 = new PurchaseProductDto(&quot;book2&quot;, &quot;user2&quot;);<br><br>   HttpHeaders headers = new HttpHeaders();<br>   headers.set(&quot;X-COM-PERSIST&quot;, &quot;true&quot;);<br><br>   HttpEntity&lt;PurchaseProductDto&gt; request1 = new HttpEntity&lt;&gt;(purchaseProductDto1, headers);<br>   HttpEntity&lt;PurchaseProductDto&gt; request2 = new HttpEntity&lt;&gt;(purchaseProductDto2, headers);<br><br>   Thread thread1 = new Thread(new PostRequestTask&lt;&gt;(url, request1));<br>   Thread thread2 = new Thread(new PostRequestTask&lt;&gt;(url, request2));<br>   thread1.start();<br>   thread2.start();<br>   thread1.join();<br>   thread2.join();<br><br><br>   System.<em>out</em>.println(MessageBroker.<em>messages</em>);<br>   <em>assertEquals</em>(2, MessageBroker.<em>eventsCount</em>.get(),<br>         &quot;number of ProductPurchasedEvent instances: &quot; + MessageBroker.<em>eventsCount</em>.get());<br>   <em>assertNotEquals</em>(MessageBroker.<em>messages</em>.get(0).getEventId(), MessageBroker.<em>messages</em>.get(1).getEventId());<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1AyW9dgJ_7ygfl4LHEkyQ.png" /><figcaption>result of testDefaultBehaviorOfPrototypeWithSingleton</figcaption></figure><p>Both assertions fails.</p><p><strong>What happened?!</strong><br>If we look at the console log we’ll see that we have two different message content but with same eventId which is weird. Also we know that the constructor has been called just one time, which eventsCount value (=1) proves it. <br>This is what happened: spring created only one instance of ProductPurchasedEvent. This is the default behavior of spring when a singleton has a prototype dependency (unless we customize it). It eagerly creates and injects all dependent objects at the application startup level.<br>Look at the mess now! Two different events published to the message broker but with same id which we could anticipate that the message broker will ignore the second one. <em>This is a </em><strong><em>Data Loss! </em></strong>Or maybe does something else (based on configurations), but surely not what we intended.</p><p>Spring supports proxy pattern with injecting prototype beans which means instead of injecting a real bean itself we inject a proxy object that delegates all the work to the real created beans. (<em>for more details see </em><a href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-proxying"><em>spring documentation</em></a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*vXCR2cs5VStLO2eYPacGgQ.png" /></figure><p>If we enable TARGET_CLASS proxy mode on our prototype class, spring creates a new instance for every method call of prototype. let’s test our scenario, this time with proxy mode enabled.</p><pre>@Data<br>@Component<br>@Scope(value = &quot;prototype&quot;, proxyMode = ScopedProxyMode.<em>TARGET_CLASS</em>)<br>public class ProductPurchasedEvent2 {<br>    private String product;<br>    private String buyer;<br>    private String eventId;<br><br>    ProductPurchasedEvent2() {<br>        this.eventId = RandomStringUtils.<em>randomAlphanumeric</em>(10);<br>        MessageBroker.<em>eventsCount</em>.incrementAndGet();<br>        MessageBroker.<em>createdEventsIdList</em>.add(eventId);<br>    }<br><br>    public boolean fire() {<br>        String message = buyer + &quot; purchased &quot; + product;<br>        System.<em>out</em>.println(&quot;Thread fire: &quot; + Thread.<em>currentThread</em>().getName() + &quot; &quot; + message + &quot; eventId: &quot; + eventId);<br>        MessageBroker.<em>messages</em>.add(new Message(eventId, message));<br>        return true;<br>    }<br>}</pre><p>And this is our test case:</p><pre>@Test<br>@SneakyThrows<br>void testProxiedPrototypeWithSingleton() {<br>   final String baseUrl = &quot;http://localhost:&quot;+randomServerPort+&quot;/purchase/with-proxy&quot;;<br>   URI url = new URI(baseUrl);<br>   PurchaseProductDto purchaseProductDto1 = new PurchaseProductDto(&quot;book1&quot;, &quot;user1&quot;);<br>   PurchaseProductDto purchaseProductDto2 = new PurchaseProductDto(&quot;book2&quot;, &quot;user2&quot;);<br><br>   HttpHeaders headers = new HttpHeaders();<br>   headers.set(&quot;X-COM-PERSIST&quot;, &quot;true&quot;);<br><br>   HttpEntity&lt;PurchaseProductDto&gt; request1 = new HttpEntity&lt;&gt;(purchaseProductDto1, headers);<br>   HttpEntity&lt;PurchaseProductDto&gt; request2 = new HttpEntity&lt;&gt;(purchaseProductDto2, headers);<br><br>   Thread thread1 = new Thread(new PostRequestTask&lt;&gt;(url, request1));<br>   Thread thread2 = new Thread(new PostRequestTask&lt;&gt;(url, request2));<br>   thread1.start();<br>   thread2.start();<br>   thread1.join();<br>   thread2.join();<br><br><br>   System.<em>out</em>.println(&quot;messages list: &quot; + MessageBroker.<em>messages</em>);<br>   System.<em>out</em>.println(&quot;eventId list: &quot; + MessageBroker.<em>createdEventsIdList</em>);<br>   <em>assertEquals</em>(2, MessageBroker.<em>eventsCount</em>.get(),<br>         &quot;number of ProductPurchasedEvent instances: &quot; + MessageBroker.<em>eventsCount</em>.get());<br>   <em>assertNotEquals</em>(MessageBroker.<em>messages</em>.get(0).getEventId(), MessageBroker.<em>messages</em>.get(1).getEventId());<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NURx6XWNQsJOpPLoFENK7w.png" /><figcaption>result of testProxiedPrototypeWithSingleton</figcaption></figure><p>We now have 7 distinct instances and one Message in MessageBroker with wrong data. even worse! It’s because every time we call a method of a proxied prototype, spring creates a new instance. So each time one of the setters is called the newly created bean will be in a state that just the value of the related setter is set and other fields values remain null (calling fire methods after two setters in this case).</p><h4>So What Should We Do?</h4><p>Spring introduces something called object factory/provider which enables us to create dependency instances programmatically, on demand every time it is needed by calling getObject() method. This is a solution to our problem so let’s try and test it:</p><pre>@Service<br>public class PurchaseServiceWithObjectFactory {<br>    private final ObjectProvider&lt;ProductPurchasedEvent&gt; productPurchasedEventObjectFactory;<br><br><br>    public PurchaseServiceWithObjectFactory(<br>            ObjectProvider&lt;ProductPurchasedEvent&gt; productPurchasedEventObjectFactory<br>    ) {<br>        this.productPurchasedEventObjectFactory = productPurchasedEventObjectFactory;<br>    }<br><br>    public boolean purchase(PurchaseProductDto dto) {<br>        System.<em>out</em>.println(&quot;Thread: &quot; + Thread.<em>currentThread</em>().getName() + &quot;product: &quot; + dto.getProduct() + &quot; purchased successfully&quot;);<br>        ProductPurchasedEvent productPurchasedEventInstance = productPurchasedEventObjectFactory.getObject();<br>        productPurchasedEventInstance.setProduct(dto.getProduct());<br>        productPurchasedEventInstance.setBuyer(dto.getBuyer());<br>        productPurchasedEventInstance.fire();<br>        return true;<br>    }<br>}</pre><p>This new service uses ObjectProvider.</p><pre>@Test<br>@SneakyThrows<br>void testPrototypeObjectFactoryWithSingleton() {<br>   final String baseUrl = &quot;http://localhost:&quot;+randomServerPort+&quot;/purchase/with-object-factory&quot;;<br>   URI url = new URI(baseUrl);<br>   PurchaseProductDto purchaseProductDto1 = new PurchaseProductDto(&quot;book1&quot;, &quot;user1&quot;);<br>   PurchaseProductDto purchaseProductDto2 = new PurchaseProductDto(&quot;book2&quot;, &quot;user2&quot;);<br><br>   HttpHeaders headers = new HttpHeaders();<br>   headers.set(&quot;X-COM-PERSIST&quot;, &quot;true&quot;);<br><br>   HttpEntity&lt;PurchaseProductDto&gt; request1 = new HttpEntity&lt;&gt;(purchaseProductDto1, headers);<br>   HttpEntity&lt;PurchaseProductDto&gt; request2 = new HttpEntity&lt;&gt;(purchaseProductDto2, headers);<br><br>   Thread thread1 = new Thread(new PostRequestTask&lt;&gt;(url, request1));<br>   Thread thread2 = new Thread(new PostRequestTask&lt;&gt;(url, request2));<br>   thread1.start();<br>   thread2.start();<br>   thread1.join();<br>   thread2.join();<br><br><br>   System.<em>out</em>.println(&quot;messages list: &quot; + MessageBroker.<em>messages</em>);<br>   System.<em>out</em>.println(&quot;eventId list: &quot; + MessageBroker.<em>createdEventsIdList</em>);<br>   <em>assertEquals</em>(2, MessageBroker.<em>eventsCount</em>.get(),<br>         &quot;number of ProductPurchasedEvent instances: &quot; + MessageBroker.<em>eventsCount</em>.get());<br>   <em>assertNotEquals</em>(MessageBroker.<em>messages</em>.get(0).getEventId(), MessageBroker.<em>messages</em>.get(0).getEventId());<br><br>}</pre><p>Once again we test our scenario</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zd6mb5PPzHKWnNYX8DaHng.png" /></figure><p><strong>And it fails again!</strong> This is because one redundant instance is automatically (instead of programmatically) created and injected at application startup which our clues and console logs proves it. <br>We could easily brush aside the first one and refactor our test.</p><pre>@Test<br>@SneakyThrows<br>void testPrototypeObjectFactoryWithSingleton() {<br>   final String baseUrl = &quot;http://localhost:&quot;+randomServerPort+&quot;/purchase/with-object-factory&quot;;<br>   URI url = new URI(baseUrl);<br>   PurchaseProductDto purchaseProductDto1 = new PurchaseProductDto(&quot;book1&quot;, &quot;user1&quot;);<br>   PurchaseProductDto purchaseProductDto2 = new PurchaseProductDto(&quot;book2&quot;, &quot;user2&quot;);<br><br>   HttpHeaders headers = new HttpHeaders();<br>   headers.set(&quot;X-COM-PERSIST&quot;, &quot;true&quot;);<br><br>   HttpEntity&lt;PurchaseProductDto&gt; request1 = new HttpEntity&lt;&gt;(purchaseProductDto1, headers);<br>   HttpEntity&lt;PurchaseProductDto&gt; request2 = new HttpEntity&lt;&gt;(purchaseProductDto2, headers);<br><br>   Thread.<em>sleep</em>(5000);<br>   // getting initial eventId value before sending http requests<br>   String initEventId = MessageBroker.<em>createdEventsIdList</em>.get(0);<br>   System.<em>out</em>.println(&quot;####################### DELAY ##########################&quot;);<br><br>   Thread thread1 = new Thread(new PostRequestTask&lt;&gt;(url, request1));<br>   Thread thread2 = new Thread(new PostRequestTask&lt;&gt;(url, request2));<br>   thread1.start();<br>   thread2.start();<br>   thread1.join();<br>   thread2.join();<br><br><br>   System.<em>out</em>.println(&quot;messages list: &quot; + MessageBroker.<em>messages</em>);<br>   System.<em>out</em>.println(&quot;eventId list: &quot; + MessageBroker.<em>createdEventsIdList</em>);<br><br>   // we could ignore first created instance so 3 is ok.<br>   <em>assertEquals</em>(3, MessageBroker.<em>eventsCount</em>.get(),<br>         &quot;number of ProductPurchasedEvent instances: &quot; + MessageBroker.<em>eventsCount</em>.get());<br>   // if event instances are 3 the first one should be equal to initial eventId set at application startup<br>   <em>assertEquals</em>(initEventId, MessageBroker.<em>createdEventsIdList</em>.get(0));<br><br>   // finally messages delivered to message broker should not have same event id<br>   <em>assertNotEquals</em>(MessageBroker.<em>messages</em>.get(0).getEventId(), MessageBroker.<em>messages</em>.get(1).getEventId());<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0V1Mt_XRGFU9mKk02tWOw.png" /></figure><p>This time we got green and our test case passed. So we could drink our coffee and be happy :)</p><h4>Conclusion:</h4><ol><li>most of the times we don’t need to use prototype and default singletons are good enough. So <strong>don’t use prototype (also session and request) unless you really need it</strong>.</li><li>if you design your singleton beans <strong>stateless </strong>you are guaranteed that won’t face thread safety issues.</li><li>but if you decide to use prototype,<strong> be aware of the way you use it</strong> matches your scenario and expectations.</li></ol><p>I tried to demonstrate the problem with a TDD like approach but for keeping simplicity and focusing on the topic didn’t try to put all the testing and coding best practices in it. So be kind and feel free to point any issue and comment it out :)<br><a href="https://github.com/miladro1/spring-boot-trhead-safety">here’s all the codes on github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8c8d3aecbee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>