<?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 El mansouri Houssam on Medium]]></title>
        <description><![CDATA[Stories by El mansouri Houssam on Medium]]></description>
        <link>https://medium.com/@elmansouri.houssam?source=rss-2fdd839a62a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lznYbo638hoZD5sJClYO8Q.jpeg</url>
            <title>Stories by El mansouri Houssam on Medium</title>
            <link>https://medium.com/@elmansouri.houssam?source=rss-2fdd839a62a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:16:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elmansouri.houssam/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[Watching Spring Create a Bean — Lazily — From the Inside]]></title>
            <link>https://medium.com/@elmansouri.houssam/watching-spring-create-a-bean-lazily-from-the-inside-0b2dfac891a1?source=rss-2fdd839a62a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b2dfac891a1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[El mansouri Houssam]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 11:27:59 GMT</pubDate>
            <atom:updated>2026-04-26T11:27:59.850Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A debugger walkthrough of </em><em>DefaultListableBeanFactory, with screenshots of the actual call chain</em></p><p>In the following article we&#39;ll see line by line how the bean get created, So I stripped Spring down to its barest skeleton: no @ComponentScan, no auto-configuration, no ApplicationContext. Just a raw DefaultListableBeanFactory, one bean, and a debugger.</p><p>What I found was that the “magic” of Spring is, at this layer, just a chain of method calls, nine stops from getBean(UserService.class) to the point where the bean is actually about to be created. And along the way, I learned something about Spring that almost no one explains correctly: <strong>when you use a raw </strong><strong>BeanFactory, beans are lazy by default.</strong></p><p>This article walks through that journey, with screenshots at every step.</p><h3>The setup</h3><p>Here’s the minimal main method:</p><pre>package org.example.springbootdemo;<br><br>import org.example.springbootdemo.service.UserService;<br>import org.springframework.beans.factory.config.BeanDefinition;<br>import org.springframework.beans.factory.support.BeanDefinitionBuilder;<br>import org.springframework.beans.factory.support.DefaultListableBeanFactory;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>import java.util.Arrays;<br><br>@SpringBootApplication<br>public class SpringBootDemoApplication {<br><br>    public static void main(String[] args) {<br>        // Create the minimal container<br>        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();<br><br>        // Manually register a bean definition<br>        BeanDefinition beanDef = BeanDefinitionBuilder<br>                .rootBeanDefinition(UserService.class)<br>                .addPropertyReference(&quot;userService&quot;, &quot;userService&quot;)<br>                .getBeanDefinition();<br><br>        beanFactory.registerBeanDefinition(&quot;userService&quot;, beanDef);<br><br>        System.out.println(&quot;BeanFactory created - but NO beans instantiated yet!&quot;);<br>        System.out.println(&quot;Registered beans: &quot; + Arrays.toString(beanFactory.getBeanDefinitionNames()));<br><br>        // NOW the bean gets created (lazy loading)<br>        UserService service = beanFactory.getBean(UserService.class);<br>        System.out.println(&quot;UserService created: &quot; + service);<br>    }<br><br>}</pre><p>UserService has a constructor that prints when it runs. The output:</p><pre>BeanFactory created - but NO beans instantiated yet!<br>Registered beans: [userService]<br>UserService created: UserService@305b7c14 (self=SAME instance)<br>Disconnected from the target VM, address: &#39;127.0.0.1:57928&#39;, transport: &#39;socket&#39;</pre><p>Notice the order. The bean <strong>definition</strong> is registered before the constructor runs. The bean <strong>instance</strong> doesn’t exist until getBean() is called.</p><p>That single observation is the whole article. Now let’s see <em>why</em>, by stepping through the source.</p><h3>Bean definition vs bean instance — a critical distinction</h3><p>Before we hit the debugger, internalize this:</p><ul><li><strong>Bean definition</strong> = metadata. A small data structure stored in a Map&lt;String, BeanDefinition&gt; inside the factory. It says: <em>&quot;there&#39;s a bean named userService, of class UserService, scoped as singleton.&quot;</em> No object exists yet.</li><li><strong>Bean instance</strong> = the actual Java object. Created by reflection, populated with dependencies, initialized.</li></ul><p>Spring keeps these two <strong>strictly separate</strong>. Registration is cheap and metadata-only. Instantiation happens later, on demand.</p><h3>The journey: from getBean() to the moment of creation</h3><p>I set a single breakpoint on this line:</p><pre>UserService service = beanFactory.getBean(UserService.class);</pre><p>Then I <strong>clicked on (Step Into)</strong> and followed the code wherever it led. Here’s what I saw, in order.</p><h3>Stop 1 — DefaultListableBeanFactory.getBean(Class) — line 385</h3><p>The very first method we land in. It’s a one-liner that delegates to a more general overload:</p><pre>return getBean(requiredType, (Object[]) null);</pre><p>Look at the call stack at the bottom of the screenshot: only main and getBean are on it. We&#39;re at the very beginning of the journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IB_vFbeVYBdpMuDVAz3UiA.png" /></figure><p>This method does nothing interesting, it just forwards the call with null args. But notice the variables panel: requiredType is the Class&lt;UserService&gt; we passed in, and the this is our DefaultListableBeanFactory instance with defining beans [userService...]. The bean definition is registered. The bean instance does not exist yet.</p><h3>Stop 2 — DefaultListableBeanFactory.resolveBean(...) — line 563</h3><p>We’ve stepped into the next method, resolveBean. This is where Spring starts the actual work of finding which bean matches the requested type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sC2W8iHAGBmyxCtTK6M_7w.png" /></figure><p>Notice in the variables panel: nonUniqueAsNull = false, args = null. We don&#39;t yet have a beanName — Spring is about to look it up by type. The whole point of this method is to ask: <em>&quot;of all the beans I know about, which one matches </em><em>UserService?&quot;</em></p><p>The method handles parent factories too (the else if (parent != null) block), but since our factory has no parent, we descend into resolveNamedBean.</p><h3>Stop 3 — DefaultListableBeanFactory.resolveNamedBean(ResolvableType, ...) — line 1540</h3><p>Now we’re in the real type-resolution logic:</p><pre>String[] candidateNames = getBeanNamesForType(requiredType);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9qJIESe8Te4-iIErbaqBw.png" /></figure><p>This call iterates over the registered bean definitions and returns the names of beans whose type matches UserService. In our case, since we only registered one bean of that type, candidateNames should contain exactly one entry: &quot;userService&quot;.</p><p>The method goes on to handle three cases: <strong>multiple candidates</strong> (it tries to find a primary or unique one), <strong>exactly one candidate</strong>, or <strong>no candidates</strong> (returns null).</p><h3>Stop 4 — Same method, line 1555 — candidate found</h3><p>A few lines later, after getBeanNamesForType returned, Spring evaluates:</p><pre>if (candidateNames.length == 1) {<br>    return resolveNamedBean(candidateNames[0], requiredType, args);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVmnRH1J2X-ROoDpwjtvcA.png" /></figure><p>Look at the variables panel — this is the moment of truth:</p><pre>candidateNames = {String[1]@2243} [&quot;userService&quot;]<br>candidateNames.length = 1<br>candidateNames[0] = &quot;userService&quot;</pre><p><strong>We’ve crossed a threshold.</strong> Up until this point, Spring was working with a Class. Now it has a String. Internally, Spring is name-based, every bean is identified by a name, and that name is the key into all the caches it uses to track instances.</p><p>The single candidate path calls a different overload of resolveNamedBean, this time taking the bean name directly.</p><h3>Stop 5 — DefaultListableBeanFactory.resolveNamedBean(String beanName, ...) — line 1598</h3><pre>Object bean = getBean(beanName, (Class) null, args);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlDZ02ktjxdOK1fznBCWCg.png" /></figure><p>Variables panel now shows:</p><pre>beanName = &quot;userService&quot;<br>requiredType = &quot;org.example.springbootdemo.service.UserService&quot;<br>args = null</pre><p>We’re about to call getBean(String, Class, Object[]) — but this overload is defined in the parent class AbstractBeanFactory, not DefaultListableBeanFactory. So when we step in, the file changes.</p><h3>Stop 6 — AbstractBeanFactory.getBean(String, Class, Object...) — line 227</h3><p>We’ve left DefaultListableBeanFactory and are now in its parent class AbstractBeanFactory. This is where the real container logic begins. The method is again a one-liner:</p><pre>return doGetBean(name, requiredType, args, false);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwI9NY3YJFMz7bkvj2UnVw.png" /></figure><p>This is essentially a public→protected handoff. getBean is the public API; doGetBean is the protected internal master method. You can see the Javadoc above the method describing the parameters: name, requiredType, args, typeCheckOnly. The last one — typeCheckOnly = false — tells Spring &quot;this is a real lookup, not just a type check, so go ahead and create the bean if needed.&quot;</p><p>doGetBean is the most important method in the entire Spring container. Everything passes through it.</p><h3>Stop 7 — AbstractBeanFactory.doGetBean(...) — line 246</h3><p>Now we’re in the master method. The first three lines do something profound:</p><p>java</p><pre>String beanName = transformedBeanName(name);          // line 246<br>Object beanInstance;<br>// Eagerly check singleton cache for manually registered singletons.<br>Object sharedInstance = getSingleton(beanName);       // line 250 — the cache check<br>if (sharedInstance != null &amp;&amp; args == null) {<br>    if (logger.isTraceEnabled()) { ... }<br>    beanInstance = getObjectForBeanInstance(...);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DI-2RgWmD1wbgISVIiygQ.png" /></figure><p>This is the <strong>cache check</strong>. getSingleton(beanName) looks in three internal maps:</p><ul><li>singletonObjects — fully initialized beans</li><li>earlySingletonObjects — instantiated but not yet populated (used during circular dependency resolution)</li><li>singletonFactories — factories that can produce an early reference</li></ul><p>For userService on the first call, all three are empty. getSingleton returns null. So sharedInstance == null, and we skip the early-return branch entirely.</p><p>Notice the comment in the source: <strong>“Eagerly check singleton cache for manually registered singletons.”</strong> Spring is telling us: <em>“if someone already created this bean and stuck it in the cache, just return it — don’t bother going through the creation machinery.”</em> This is also why repeated getBean() calls are fast — only the first call does real work.</p><h3>Stop 8 — Same method, line 293 — markBeanAsCreated</h3><p>We’ve fallen through to the creation path. Before any actual creation happens, Spring runs:</p><pre>if (!typeCheckOnly) {<br>    markBeanAsCreated(beanName);   // line 293<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ee9h7RtTOUwyZ3xonLuDmw.png" /></figure><p>The variables panel confirms what we expect:</p><pre>beanName = &quot;userService&quot;<br>sharedInstance = null     ← cache was empty<br>parentBeanFactory = null  ← we have no parent<br>typeCheckOnly = false</pre><p>markBeanAsCreated(beanName) adds &quot;userService&quot; to a Set&lt;String&gt; of beans whose creation has begun. This set is a tripwire — if anything tries to <em>change</em> the bean definition after this point, Spring knows: <em>&quot;too late, you&#39;ve already started creating it.&quot;</em> It&#39;s how Spring guarantees that bean definitions are stable once instantiation has begun.</p><h3>Stop 9 — Same method, line 337 — the creation call</h3><p>This is the climax. After loading the merged bean definition and resolving any dependsOn declarations, Spring reaches the real creation logic:</p><pre>// Create bean instance.<br>if (mbd.isSingleton()) {<br>    sharedInstance = getSingleton(beanName, () -&gt; {     // line 337<br>        try {<br>            return createBean(beanName, mbd, args);<br>        } catch (BeansException ex) {<br>            destroySingleton(beanName);<br>            throw ex;<br>        }<br>    });<br>    beanInstance = getObjectForBeanInstance(...);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtW7Xw_LucxvuN07GlUlmQ.png" /></figure><p>Look closely at the variables panel:</p><pre>sharedInstance = null<br>beanName = &quot;userService&quot;<br>mbd = &quot;Root bean: class=org.example.springbootdemo.service.UserService; scope=singleton...&quot;</pre><p>The merged bean definition is loaded, scope is singleton, and sharedInstance is null — confirming we&#39;re going through the create path.</p><p>This call to getSingleton(beanName, ObjectFactory) is <strong>the second overload</strong> of getSingleton — different from the one at Stop 7. The first one was a read-only cache check. This one takes a lambda (ObjectFactory) that knows how to create the bean. Inside getSingleton, Spring will:</p><ol><li>Lock the singleton creation (so two threads don’t try to make the same singleton).</li><li>Call beforeSingletonCreation(beanName) — adds the name to a singletonsCurrentlyInCreation set (the tripwire for circular dependency detection).</li><li>Invoke the lambda → createBean(beanName, mbd, args) → doCreateBean(...) → createBeanInstance(...) → and at last, <strong>the constructor of </strong><strong>UserService runs</strong>.</li><li>Call addSingleton(beanName, instance) — moves the finished bean into the singletonObjects map.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*m1NVmU-djFdkIv7huAAV6A.gif" /></figure><h3>So is Spring lazy or eager? Both — and that’s the point</h3><p>In <strong>my code</strong> — using raw DefaultListableBeanFactory — the bean was created lazily. The constructor only ran when I explicitly called getBean(). If I had never called getBean(), the bean would never have been instantiated. Period.</p><p>But in a normal Spring or Spring Boot application, that’s <strong>not what happens</strong>. Real apps use ApplicationContext (specifically AnnotationConfigApplicationContext, or what Spring Boot wires up for you). And ApplicationContext does something extra: during its refresh() lifecycle, it calls a method named preInstantiateSingletons(), which loops over every singleton bean definition and calls getBean() on each one — <strong>before any of your code runs</strong>.</p><p>So in a real app, by the time main continues past SpringApplication.run(...), every singleton has already been created. That&#39;s eager instantiation. It&#39;s the default because eager fail-fast is what you want in production — if a bean is broken, you want startup to fail, not the first user request three hours later.</p><p>The clean mental model:</p><blockquote><strong><em>Bean creation is decoupled from bean registration.</em></strong><em> Registration just stores metadata. The actual instantiation happens later — either when </em><em>preInstantiateSingletons is called during context refresh (the </em><em>ApplicationContext default), or when someone explicitly calls </em><em>getBean (the only trigger in raw </em><em>BeanFactory).</em></blockquote><p>The “Spring is lazy” or “Spring is eager” debate is the wrong question. The right question is <strong>which container are you using and when does it choose to call </strong><strong>getBean</strong>.</p><h3>Try it yourself</h3><p>If you want to reproduce this:</p><ol><li>Create a Spring Boot project with only spring-boot-starter as a dependency. No web, no data, no nothing.</li><li>Replace your main with the snippet at the top of this article.</li><li>Add a UserService class with a println in the constructor.</li><li><strong>Click “Download Sources”</strong> when IntelliJ shows the yellow banner — this gives you the real, commented Spring source instead of decompiled bytecode.</li><li>Set a breakpoint on beanFactory.getBean(UserService.class).</li><li>Click the bug icon. When it pauses, press <strong>F7 (Step Into)</strong> repeatedly.</li></ol><p>You’ll travel exactly the path shown in the screenshots above. The whole journey takes about two minutes. By the end, the IoC container will have stopped feeling like magic.</p><p>That’s the goal of debugging Spring from the inside: not to memorize methods, but to <strong>see</strong> that there’s no magic in there. Just maps, methods, and a chain of delegation.</p><p>Next up in this series: what happens <strong>inside</strong> doCreateBean — the three-phase bean lifecycle (instantiate → populate → initialize), and how Spring resolves circular dependencies using a three-level cache. Stay tuned.</p><p>Connect with me on LinkedIn — <a href="https://www.linkedin.com/in/elmanhou/">Houssam El Mansouri</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b2dfac891a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Core Container Deep Dive]]></title>
            <link>https://medium.com/@elmansouri.houssam/spring-core-container-deep-dive-443a0f8355da?source=rss-2fdd839a62a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/443a0f8355da</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[El mansouri Houssam]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 20:45:44 GMT</pubDate>
            <atom:updated>2025-09-23T22:26:33.984Z</atom:updated>
            <content:encoded><![CDATA[<p>In the following article, you will discover the magic of Spring.</p><h3>Section 1: BeanFactory vs ApplicationContext — The Foundation</h3><p>the blatant truth: ApplicationContext IS-A BeanFactory + extra functionalities</p><pre>// ApplicationContext extends BeanFactory<br>public interface ApplicationContext extends <br>    EnvironmentCapable, <br>    ListableBeanFactory,     // &lt;-- This extends BeanFactory<br>    HierarchicalBeanFactory,  // &lt;-- This extends BeanFactory<br>    MessageSource, <br>    ApplicationEventPublisher, <br>    ResourcePatternResolver {<br>}</pre><p>Visual representation:</p><pre>ApplicationContext <br>├── 🏭 BeanFactory (does actual bean creation)<br>├── 📢 Event System<br>├── 🌍 Internationalization  <br>├── 📁 Resource Loading<br>├── 🔄 Environment &amp; Profiles<br>└── 🎯 Auto-configuration Support</pre><p>Let us get hands-on with ApplicationContext.</p><pre>public static void main(String[] args) {<br>        // Create the minimal container<br>        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();<br><br>        // Manually register a bean definition<br>        BeanDefinition beanDef = BeanDefinitionBuilder<br>                .rootBeanDefinition(UserService.class)<br>                .addPropertyReference(&quot;userService&quot;, &quot;userService&quot;)<br>                .getBeanDefinition();<br><br>        beanFactory.registerBeanDefinition(&quot;userService&quot;, beanDef);<br><br>        // Register dependency<br>        BeanDefinition repoDef = BeanDefinitionBuilder<br>                .rootBeanDefinition(UserService.class)<br>                .getBeanDefinition();<br><br>        beanFactory.registerBeanDefinition(&quot;userService&quot;, repoDef);<br><br>        System.out.println(&quot;BeanFactory created - but NO beans instantiated yet!&quot;);<br>        System.out.println(&quot;Registered beans: &quot; + Arrays.toString(beanFactory.getBeanDefinitionNames()));<br><br>        <br>        UserService service = beanFactory.getBean(UserService.class);<br>        System.out.println(&quot;UserService created: &quot; + service);<br><br>        // Second call returns same instance (singleton)<br>        UserService service2 = beanFactory.getBean(UserService.class);<br>        System.out.println(&quot;Same instance? &quot; + (service == service2));<br>    }</pre><p>1 — Minimal container</p><pre>DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();</pre><p>Think of it as an empty box.</p><p>2 — Manually defining a bean</p><pre>BeanDefinition beanDef = BeanDefinitionBuilder<br>        .rootBeanDefinition(UserService.class)<br>        .addPropertyReference(&quot;userService&quot;, &quot;userService&quot;)<br>        .getBeanDefinition();<br><br>beanFactory.registerBeanDefinition(&quot;userService&quot;, beanDef);</pre><p>3 — Lazy nature of BeanFactory</p><pre>System.out.println(&quot;BeanFactory created - but NO beans instantiated yet!&quot;);<br>System.out.println(&quot;Registered beans: &quot; + Arrays.toString(beanFactory.getBeanDefinitionNames()));</pre><p>4 — Getting a bean</p><pre>UserService service = beanFactory.getBean(UserService.class);<br>System.out.println(&quot;UserService created: &quot; + service);</pre><p>At this phase, Spring actually <strong>instantiates </strong><strong>UserService</strong>.</p><p>Let’s dive deeper into the code above.</p><p>Let us put the breakpoint at the following line</p><pre>beanFactory.registerBeanDefinition(&quot;userService&quot;, beanDef);</pre><p>Once you step into it, you’ll see the following method definition.</p><pre>public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {<br>        Assert.hasText(beanName, &quot;Bean name must not be empty&quot;);<br>        Assert.notNull(beanDefinition, &quot;BeanDefinition must not be null&quot;);<br>        if (beanDefinition instanceof AbstractBeanDefinition abd) {<br>            try {<br>                abd.validate();<br>            } catch (BeanDefinitionValidationException ex) {<br>                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, &quot;Validation of bean definition failed&quot;, ex);<br>            }<br>        }<br><br>        BeanDefinition existingDefinition = (BeanDefinition)this.beanDefinitionMap.get(beanName);<br>        if (existingDefinition != null) {<br>            if (!this.isBeanDefinitionOverridable(beanName)) {<br>                throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);<br>            }<br><br>            this.logBeanDefinitionOverriding(beanName, beanDefinition, existingDefinition);<br>            this.beanDefinitionMap.put(beanName, beanDefinition);<br>        } else {<br>            if (this.isAlias(beanName)) {<br>                String aliasedName = this.canonicalName(beanName);<br>                if (!this.isBeanDefinitionOverridable(aliasedName)) {<br>                    if (this.containsBeanDefinition(aliasedName)) {<br>                        throw new BeanDefinitionOverrideException(beanName, beanDefinition, this.getBeanDefinition(aliasedName));<br>                    }<br><br>                    throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, &quot;Cannot register bean definition for bean &#39;&quot; + beanName + &quot;&#39; since there is already an alias for bean &#39;&quot; + aliasedName + &quot;&#39; bound.&quot;);<br>                }<br><br>                if (this.logger.isInfoEnabled()) {<br>                    this.logger.info(&quot;Removing alias &#39;&quot; + beanName + &quot;&#39; for bean &#39;&quot; + aliasedName + &quot;&#39; due to registration of bean definition for bean &#39;&quot; + beanName + &quot;&#39;: [&quot; + String.valueOf(beanDefinition) + &quot;]&quot;);<br>                }<br><br>                this.removeAlias(beanName);<br>            }<br><br>            if (this.hasBeanCreationStarted()) {<br>                synchronized(this.beanDefinitionMap) {<br>                    this.beanDefinitionMap.put(beanName, beanDefinition);<br>                    List&lt;String&gt; updatedDefinitions = new ArrayList(this.beanDefinitionNames.size() + 1);<br>                    updatedDefinitions.addAll(this.beanDefinitionNames);<br>                    updatedDefinitions.add(beanName);<br>                    this.beanDefinitionNames = updatedDefinitions;<br>                    this.removeManualSingletonName(beanName);<br>                }<br>            } else {<br>                this.beanDefinitionMap.put(beanName, beanDefinition);<br>                this.beanDefinitionNames.add(beanName);<br>                this.removeManualSingletonName(beanName);<br>            }<br><br>            this.frozenBeanDefinitionNames = null;<br>        }<br><br>        if (existingDefinition == null &amp;&amp; !this.containsSingleton(beanName)) {<br>            if (this.isConfigurationFrozen()) {<br>                this.clearByTypeCache();<br>            }<br>        } else {<br>            this.resetBeanDefinition(beanName);<br>        }<br><br>        if (beanDefinition.isPrimary()) {<br>            this.primaryBeanNames.add(beanName);<br>        }<br><br>    }</pre><p>Take a look at the following line where the bean definition is declared.</p><pre>this.beanDefinitionMap.put(beanName, beanDefinition);</pre><p>This is where Spring <strong>stores your bean definition</strong> in an internal map (beanDefinitionMap).<br> Later, when you call getBean(...), Spring looks it up here, then <strong>instantiates and wires it</strong>.</p><p>The diagram below demystifies what we’ve been explaining.</p><pre>Step 1: Register Bean Definition<br>--------------------------------<br>beanFactory.registerBeanDefinition(&quot;userService&quot;, beanDef)<br>               │<br>               ▼<br>        beanDefinitionMap.put(beanName, beanDefinition)<br>               │<br>               ▼<br>   Bean definition stored in container (metadata only)<br><br>Step 2: Request Bean<br>-------------------<br>UserService service = beanFactory.getBean(UserService.class)<br>               │<br>               ▼<br>Container checks beanDefinitionMap for &quot;userService&quot;<br>               │<br>               ▼<br>Does bean instance already exist in singleton cache?<br>      ┌─────────────┐<br>      │ Yes → return │<br>      │ existing     │<br>      │ instance     │<br>      └─────────────┘<br>      │<br>      ▼<br>      No → instantiate bean using definition<br>               │<br>               ▼<br>Wire dependencies (if any)<br>               │<br>               ▼<br>Store instance in singleton cache<br>               │<br>               ▼<br>Return bean to caller</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDPo7wUFQtxsxQ83-W-F5Q.png" /></figure><h3>Conclusion</h3><p>You&#39;ve just seen how Spring works internally:<br>1-Stores bean definitions<br>2-Delay instantiation until the end<br>3-Singleton behavior per default</p><p>Stay tuned for my next articles, where we’ll explore <strong>other Spring internals in depth</strong>.</p><p>Connect with me on LinkedIn — <a href="https://www.linkedin.com/in/elmanhou/">Houssam El Mansouri</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=443a0f8355da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambdas in a nutshell]]></title>
            <link>https://medium.com/@elmansouri.houssam/lambdas-in-a-nutshell-3a9fe366f78d?source=rss-2fdd839a62a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a9fe366f78d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javadevlopment]]></category>
            <dc:creator><![CDATA[El mansouri Houssam]]></dc:creator>
            <pubDate>Thu, 11 Jul 2024 18:42:54 GMT</pubDate>
            <atom:updated>2024-07-11T18:42:54.235Z</atom:updated>
            <content:encoded><![CDATA[<h3>What does mean a Lambda?</h3><p>Lambda expression can be understood as a representation of an anonymous function. It does not have a name, however, it has a list of parameters, a body, a return type, a void, including list of exception that can be thrown.</p><p>If you are wondering about the lambda term where it come, it originates from a system developed in academia called lambda calculus, which is used to describe computations</p><p>Before:</p><pre>Comparator&lt;Apple&gt; byWeight = new Comparator&lt;Apple&gt;() {<br>    public int compare(Apple a1, Apple a2){<br>        return a1.getWeight().compareTo(a2.getWeight());<br>    }<br>};</pre><p>After (with lambda expressions):</p><pre>Comparator&lt;Apple&gt; byWeight =<br>    (Apple a1, Apple a2) -&gt; a1.getWeight().compareTo(a2.getWeight());</pre><p>Don&#39;t frustrate if you do not understand well the lambda expression, I will explain in the following section.</p><h3>Lambda Analogy</h3><p>The lambda that we just showed you in the previous section, it contains the three following parts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*znJNM2AXLpNYWiwasg1jsQ.png" /><figcaption>A Lambda expression that is composed of three parameters.</figcaption></figure><h3>Where and how to use Lambdas?</h3><p>You may wondering where you are allowed to use lambda expressions, you can use lambda expressions in the context of a functional interface.</p><p>Don&#39;t worry if this sounds abstract, we&#39;ll explain it in detail what this means and what a functional interface is.</p><h3>Functional interface?</h3><p>A functional interface is an interface that specifies one abstract method, you already know several other functional interface in the Java API such as Comparator and Runnable</p><pre>public interface Comparator&lt;T&gt; {<br>    int compare(T o1, T o2);<br>}</pre><pre>}<br>public interface Runnable {<br>    void run(); <br>}</pre><p>what can you do with functional interfaces? Lambda expressions let you provide the implementation of the abstract method of a functional interface explicitly.</p><pre>Runnable r1 = () -&gt; System.out.println(&quot;hello world!&quot;); //Lambda expression</pre><p>equivalent to :</p><pre>Runnable r2 = new Runnable() {<br>   public void run() {<br>      System.out.println(&quot;Hello world!&quot;); <br>   }<br>}</pre><h3>Putting lambdas into practice</h3><p>Let&#39;s look at an example of how lambdas work, here is an example of a method that reads a file from a specific path.</p><pre>  public String processFile() throws IOException {<br>    try (BufferedReader br =<br>                 new BufferedReader(new FileReader(&quot;data.txt&quot;))) {<br>            return br.readLine();<br>    }<br>  }</pre><p>Let&#39;s use Functional Interface.</p><pre>@FunctionalInterface<br>public interface BufferedReaderProcessor {<br>     String process(BufferedReader b) throws IOException;<br>}</pre><p>You can now use this interface as the argument to your new processFile method</p><p>Let&#39;s pass lambda</p><pre>String oneLine =<br>    processFile((BufferedReader br) -&gt; br.readLine());</pre><p>Thank you, keep learning!</p><p>Follow me on LinkedIn for more articles: <a href="https://www.linkedin.com/in/elmanhou/">Houssam El Mansouri</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a9fe366f78d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connections and Transactions on Spring Framework.]]></title>
            <link>https://medium.com/@elmansouri.houssam/connections-and-transactions-on-spring-framework-05c71e05eaa6?source=rss-2fdd839a62a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/05c71e05eaa6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[El mansouri Houssam]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 17:22:54 GMT</pubDate>
            <atom:updated>2023-12-28T17:22:54.736Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to delay a connection acquisition till it’s needed</h3><p>Practically, holding unused database connections would have a big impact on the performance.<br>By default, Spring boot relies on HikariCP, and you need to turn off auto-commit in application.properties or application.yml files by doing the following configuration:</p><pre>spring.datasource.hikari.auto-commit=false<br>spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true</pre><pre>As rule of thumb, for local-resource JPA Transactions, it is always good<br>practice to configure the connection pool (e.g HikariCP) to disable auto-commit</pre><p>To see how a connection acquisition is delayed, consider the following method meant to isolate the main timeslots when a connection is obtained from the HikariCP connection pool.</p><pre>@Transactional<br>public void doTimeConsumingTask() throws InterruptedException {<br>    System.out.println(&quot;Waiting for a time-consuming<br>                        task that doesn&#39;t need a database connection ...&quot;);<br>    Thread.sleep(40000);<br>    System.out.println(&quot;Done, now query the database ...&quot;);<br>    System.out.println(&quot;The database connection should be acquired now ...&quot;);<br>    Author author = authorRepository.findById(1L).get();<br>    // at this point, the connection should be open<br>    Thread.sleep(40000);<br>    author.setAge(44);</pre><p>Calling this method without delaying the connection acquisition will reveal the output shown in the following Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0YMUg7Hm5ACj7PgUwsDKkA.png" /><figcaption>Figure 1: Acquire connection immediately</figcaption></figure><p>Calling the same method with connection acquisition enabled will reveal that the connection is obtained right before the first SQL is triggered. Meanwhile, this connection can be used by another thread, as shown in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWbu3XR3Ij8aIhZZRnskkw.png" /><figcaption>Figure 2:Delay connection acquisition</figcaption></figure><h3>How @Transactional annotation work?</h3><p>Let us assume that we have the following method for fetching:</p><pre>@Repository<br>public interface AuthorRepository extends JpaRepository&lt;Author, Long&gt; {<br>    Author findFirstByGenre(String genre);<br>}<br><br>@Service<br>public class BookstoreService <br>   public void fetchAuthor() {<br>        Author author = authorRepository.findFirstByGenre(&quot;Anthology&quot;);<br>    }<br>}</pre><p>Is there something missing? Yes, you’re right @Transactional annotation, means there is no transactional-context.</p><p>Via @Transactional annotation, you explicitly demarcate the transaction boundaries and ensure that one database connection should be used for the whole transactions that would happen inside our application.<br>All SQL statements will use a single isolation connection and all of them will run under the scope of the same Persistence Context.</p><pre>As a rule of thumb, use explicit (declarative) transactions even for read-only statements (e.g., SELECT) to define the proper transactional- contexts. A non-­transactional-­context refers to a context with no explicit transaction boundaries, not to a context with no physical database transaction. All database statements are executed in the context of a physical database transaction. By omitting the explicit transaction boundaries (transactional-context, begin/commit/rollback), you expose the application to<br>at least the following drawbacks with implications in performance:<br>    • By default, Hibernate will turn off autocommit mode anyway (autocommit=false) and a JDBC transaction is opened. The SQL statement runs inside this JDBC transaction and,<br>      afterwards, Hibernate closes the connection. But it doesn’t close the transaction, which remains uncommitted (remainsin the pending state), and this allows the database vendor implementation or the connection pool to take action. (The JDBC specification doesn’t impose a certain behavior for pending transactions. For example, MySQL rolls back the transaction while Oracle commits it.) You shouldn’t take this risk because, as a rule of thumb, you always must ensure that the transaction ends by committing it or rolling it back.<br>      <br>    • In the case of many small transactions (very common in applications with many concurrent requests), starting and ending a physical database transaction for every SQL<br>      statement implies a performance overhead.<br>      <br>    •  A method running in a non-transactional-context is prone to be altered by developers in order to write data. (Having a transactional-­context via @Transactional(readOnly=true)<br>      at the class/method-­level acts as a flag for the team members signaling that no writes should be added to this method and prevents writes if this flag is ignored.)<br>      <br>    • You cannot benefit from Spring optimizations for the underlying data access layer (e.g., flush mode is set to MANUAL, so Dirty Checking is skipped).<br>      <br>    • You cannot benefit from database-specific optimizations for read-­only transactions.<br>      <br>    • You don’t follow the read-only Spring built-in query-methods that are by default annotated with @Transactional (readOnly=true).<br>      <br>    • Starting with Hibernate 5.2.10, you can delay connection acquisition and this requires disabling autocommit.<br>      <br>    • There is no ACID support for a group of read-only SQL statements.</pre><h3>Why Spring Ignores @Transactional?</h3><p>Consider the following simple service:</p><pre>@Service<br>public class BookstoreService {<br>    private static final Logger log =<br>        Logger.getLogger(BookstoreService.class.getName());<br>    private final AuthorRepository authorRepository;<br><br>    public BookstoreService(AuthorRepository authorRepository) {<br>        this.authorRepository = authorRepository;<br>    }<br>    public void mainAuthor() {<br>        Author author = new Author();<br>        persistAuthor(author);<br>        notifyAuthor(author);<br>    }<br>    @Transactional(propagation = Propagation.REQUIRES_NEW)<br>    private long persistAuthor(Author author) {<br>        authorRepository.save(author);<br>        return authorRepository.count();<br>    }<br>    private void notifyAuthor(Author author) {<br>        log.info(() -&gt; &quot;Saving author: &quot; + author);<br>    }<br>}</pre><p>Adding the following configuration in your application.yml or application.properties files:</p><pre>logging.level.ROOT=INFO<br>logging.level.org.springframework.orm.jpa=DEBUG<br>logging.level.org.springframework.transaction=DEBUG<br># for Hibernate only<br>logging.level.org.hibernate.engine.transaction.internal.<br>TransactionImpl=DEBUG</pre><p>Calling the mainAuthor() method will create a new author, persist the author (viapersistAuthor()), and notify them that the account was created (via notifyAuthor()). As you can see, the persistAuthor() method was annotated with <a href="http://twitter.com/Transactional">@Transactional</a> and a new transaction is required (REQUIRES_NEW). Therefore, when persistAuthor() is called, Spring Boot should start a new transaction and run into it the save() and count() query-methods.</p><p>Running the code outputs the following relevant lines:</p><pre>Creating new transaction with name [org.springframework.data.<br>jpa.repository.support.SimpleJpaRepository.save]: PROPAGATION_<br>REQUIRED,ISOLATION_DEFAULT<br>Opened new EntityManager [SessionImpl(343534938&lt;open&gt;)] for JPA transaction<br>insert into author (age, genre, name) values (?, ?, ?)<br>Initiating transaction commit<br>Committing JPA transaction on EntityManager [SessionImpl(343534938&lt;open&gt;)]<br>Closing JPA EntityManager [SessionImpl(343534938&lt;open&gt;)] after transaction<br><br>Creating new transaction with name [org.springframework.data.<br>jpa.repository.support.SimpleJpaRepository.count]: PROPAGATION_<br>REQUIRED,ISOLATION_DEFAULT,readOnly<br>Opened new EntityManager [SessionImpl(940130302&lt;open&gt;)] for JPA transaction<br>select count(*) as col_0_0_ from author author0_<br>Initiating transaction commit<br>Committing JPA transaction on EntityManager [SessionImpl(940130302&lt;open&gt;)]<br>Closing JPA EntityManager [SessionImpl(940130302&lt;open&gt;)] after transaction</pre><p>There is no transaction that runs the persistAuthor() method as a unit-of-work. The save() and count() methods run in separate transactions. Why was <a href="http://twitter.com/Transactional">@Transactional</a> ignored?<br>There are two main reasons:</p><p>1 . <a href="http://twitter.com/Transactional">@Transactional</a> was added to a private, protected, or package-­protected method.</p><p>2 . <a href="http://twitter.com/Transactional">@Transactional</a> was added to a method defined in the<br>same class as where it is invoked.</p><pre>As a rule of thumb, @Transactional works only on public methods, and the method should be added in a class different from where it is<br>invoked.</pre><p>Follow me on LinkedIn for more articles: <a href="https://www.linkedin.com/in/elmanhou/">Houssam El Mansouri</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05c71e05eaa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Here's a guide on how to read your code.]]></title>
            <link>https://medium.com/@elmansouri.houssam/heres-a-guide-on-how-to-read-your-code-f9e58f6a8b28?source=rss-2fdd839a62a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9e58f6a8b28</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[hibernate]]></category>
            <dc:creator><![CDATA[El mansouri Houssam]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 12:13:28 GMT</pubDate>
            <atom:updated>2023-08-13T12:19:29.021Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to understand your app more easily.</h3><p>I define Understanding or investigating as a process of analyzing a software&#39;s capabilities. You may have a question rolling up your mind, what is the purpose of understanding or investigating? <br>This means, finding <em>bugs and correcting</em> software errors.</p><p><strong>De-bug = take out bugs, eliminate errors</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNNWrBk8m12y4BCB0OPYfw.png" /><figcaption>Investigating techniques</figcaption></figure><h3>Learning new technologies.</h3><p>another advantage of investigating techniques is when you want to learn how certain technologies work. <br>Moreover, debugging helped me to understand Spring Batch well.</p><h3>Understanding your app’s logic through debugging techniques.</h3><p>Debugging techniques give you a flexible way to understand your code using multiple variations such as stop/resume executing throughout breakpoints, field watchpoints, setting new values…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*TN2uzPDEx0LrmWTcuq2z-Q.png" /><figcaption>Breakpoint techniques</figcaption></figure><p>When you marked a line with a breakpoint, thus, you need to click on the button highlighted in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*hYHdcxg-S9Yx7UXASbp5Uw.png" /><figcaption>Debug button on IntelliJ</figcaption></figure><p>The image listed below demonstrates all the different components of debugging techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yady291nilIk3ioeUV6wcQ.png" /></figure><p>Strack trace is when you can see which method is called, i.e. main method invoking the method sumCloseToTarget(int[] nums, int targetSum)</p><h3>Navigating code with the debugger.</h3><p>In this section, we discuss the basic ways to navigate code with a debugger.</p><ul><li>Step over: Continue execution with the next line of code in the same method</li><li>Step into: Continue execution inside one of the methods called on the current line.</li><li>Step out: Return the execution to the method that is called the one you are investigating</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVseI8nnshxfDBoW7vIAew.png" /><figcaption>Walking through line codes.</figcaption></figure><p>The buttons that are highlighted using blue color, are used to walk through the code.</p><p>Let us assume that we have an exception through our code, but we could not specify from which point is triggered, then what I would do in this situation, here is a way, it may help you in this situation, Java Exception Breakpoints.<br>The following code snippet triggers a NullPointerException, however, I could not determine from where it’s triggered, then, this situation I could use Java Exception Breakpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEMx7Tipwh1fYWawFnKMJg.png" /><figcaption>Java Exception Breakpoints</figcaption></figure><p>The image above shows the line that is responsible for triggering the error.</p><p>To configure the Java Exception breakpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfXMk5GpEimjEvS1G1hZoQ.png" /></figure><h3>Debugging apps remotely.</h3><p>As all of you know, when you may encounter a situation that’s part of the code works locally but when you deploy it on another environment won’t work, then debugging remotely is intervening in this situation to rescue us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUCCLGaeMKiz9H_56K4WjA.png" /><figcaption>Remotely debugging</figcaption></figure><p>When you start the app that you want to remotely debug, you need to make sure you attach a debugger agent to the execution. To attach a debugger agent to a Java app execution, you add the -agentlib:jdwp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neADD53tBw0h4hOTx7qnow.png" /><figcaption>Configuration of the remote debug.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMWFcfKCK01RJob07A3TJQ.png" /></figure><h3>Investigating issues with logs.</h3><p>One of the biggest advantages of log messages is that they allow you to visualize the execution of a certain piece of code at a given time.</p><p>Remember logs help you to identify the error after it occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBaExrlp0Zlk_MnmeKZ1kg.png" /><figcaption>Logs</figcaption></figure><h3>Persisting logs.</h3><p>Persisting is one of the essential characteristics of log messages. One thing to takeaway, logs helped us to identify an error that already happened.</p><p>The following ways present how to implement persistence :</p><ul><li>Storing logs in a nonrelational database</li><li>Storing logs in files</li><li>Storing logs in a relational database</li></ul><h3>Defining log levels.</h3><p>Logging levels, also called severities, are a way to classify log messages based on their importance to your investigation.</p><p>The common log levels (severities) are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*_nPpHMRl6MSQrgOrr0-IDg.png" /><figcaption>The log severity pyramid</figcaption></figure><p>Let’s take an example of implementation of the logging with Log4j, then, to implement log capabilities, you need to add the following dependencies</p><pre>&lt;dependencies&gt;<br>&lt;dependency&gt;<br>&lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt;<br>&lt;artifactId&gt;log4j-api&lt;/artifactId&gt;<br>&lt;version&gt;2.14.1&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>&lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt;<br>&lt;artifactId&gt;log4j-core&lt;/artifactId&gt;<br>&lt;version&gt;2.14.1&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>To implement a log inside a class you need to implement the following instruction:</p><pre>public class main {<br>//...<br>private static Logger log = LogManager.getLogger();<br>//.....<br>public methodA() {<br>//..<br>log.info(&quot;Extract digits result for input {} is {}&quot;, input, list);<br>//..<br>}<br>}</pre><p>The following configuration shows how to define both an appender and a logger</p><p>You may wonder what is a logger, appender, and a formatted</p><p>here are they :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jmg4WJ3Akvr8BwEBb_bOog.png" /><figcaption>Logger, Appender, and Formatter</figcaption></figure><p>revenons à nos moutons, here is how to configure the log severities, logger, and appender</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;Configuration status=&quot;WARN&quot;&gt;<br>Defines an appender<br>&lt;Appenders&gt;<br>&lt;Console name=&quot;Console&quot; target=&quot;SYSTEM_OUT&quot;&gt;<br>&lt;PatternLayout pattern=&quot;%d{yy-MM-dd HH:mm:ss.SSS} [%t]<br>%-5level %logger{36} - %msg%n&quot;/&gt;<br>&lt;/Console&gt;<br>&lt;/Appenders&gt;<br>Defines a logger configuration<br>&lt;Loggers&gt;<br>&lt;Root level=&quot;info&quot;&gt;<br>&lt;AppenderRef ref=&quot;Console&quot;/&gt;<br>&lt;/Root&gt;<br>&lt;/Loggers&gt;<br>&lt;/Configuration&gt;</pre><p>The following image demonstrates the link between logger, formatted, ad appender</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JExSmOl0spoa0Zhl_Qhruw.png" /></figure><h3>Profiling.</h3><p>Profiling is a technique that is used to solve problems such as consumption resources, which method is running, JDBC queries executed, live thread, and memory consumption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7itSHaAMYJUNHz5ensJGMQ.png" /></figure><p>Once you start the app, VisualVM reveals the process on the left side</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uqny9unwQ_GDe4P4G0fdYg.png" /></figure><p>The following image demonstrates memory consumption when I run an API provided by the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LvfEP6r7fSzwn97A2Jb3mA.png" /></figure><p>The Threads tab offers a visual representation of the threads in execution and their states</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kKIlgj-oMTUY_ev3R0lTQ.png" /></figure><p>On the Profiler tab, you can use it to identify which methods were executed, and how many times were invoked, even you can use it to identify which queries were executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdmDZW8EeqLXCXgdmAEoZQ.png" /><figcaption>Profiler tab</figcaption></figure><p>In the following demonstration, I called the method getTodoById method two times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWJnaHGcacsveWMKlDSreQ.png" /></figure><p>I hope you will like the article, stay tuned for the next articles <br>follow me on LinkedIn: <a href="https://www.linkedin.com/in/elmanhou/">https://www.linkedin.com/in/elmanhou/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9e58f6a8b28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Apache Kafka Core]]></title>
            <link>https://medium.com/@elmansouri.houssam/the-apache-kafka-core-bf257f96ef8d?source=rss-2fdd839a62a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf257f96ef8d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[El mansouri Houssam]]></dc:creator>
            <pubDate>Sun, 11 Sep 2022 12:46:03 GMT</pubDate>
            <atom:updated>2022-09-11T12:46:03.631Z</atom:updated>
            <content:encoded><![CDATA[<p>Before digging into the Apache Kafka core, first, I am going to explain a little bit about how data going to be processed into Apache Kafka</p><p>Let us assume a producer sends a message to Kafka <em>topics, </em>the message has been sent to the <em>brokers.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*AVs9vMDU3am2RNMUKO26dA.png" /></figure><h3><strong>What are Brokers?</strong></h3><p>Brokers can be considered as a server entrenched in Apache Core. we going to create a <em>topic</em> to send our first message, till here, you see two times that I have written topic word two times, you may be wondering what is a <em>topic</em>, I am going to explain it don’t panic!.</p><h3>Topics</h3><p>Topics are where messages would be processed and sent to certain destinations, topics contain partitions, and those partitions have three fields, Leader, Replica, and Isr.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*wKcND8QZsBUuH8q8D7TZBA.png" /></figure><p>The image above demonstrates three brokers, and each broker has its own leader, e.g., let us zoom on the first partition, the leader is 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*7toSDBqmzmvi5HZQ0VuATg.png" /></figure><p>One important thing to notice, each partition gonna have a leader replica and others will be <em>followers</em>, which update their information from their partition leader replica, furthermore, consumers and producers only write or read from the leader replica of each partition, also known as a <em>happy path</em>.</p><p>But how does your producer or consumer know which partition replica is the leader? this is what we going to discover next section.</p><h3>Trip to Kafka</h3><p>The table below demystifies the components of Kafka&#39;s architecture within roles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*KO0SPkw_TrD_vzQD-t0IFQ.png" /></figure><p>Producer, Consumer, and Topic are already explained.</p><h3>Zookeeper ensemble</h3><p>As you see earlier, Kafka could have one or more brokers, these brokers need to communicate with each other. agreeing on which one is the replica leader of a partition, here where Zookeeper intercepts and done this one for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*4WwsYmgqi56Qy20VCRyuqw.png" /></figure><p>I wish this article would be beneficial for you.</p><p>My <a href="https://www.linkedin.com/in/elmanhou/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf257f96ef8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Apache Kafka]]></title>
            <link>https://medium.com/@elmansouri.houssam/introduction-to-apache-kafka-e52bc1eeeec7?source=rss-2fdd839a62a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e52bc1eeeec7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[El mansouri Houssam]]></dc:creator>
            <pubDate>Thu, 25 Aug 2022 20:14:10 GMT</pubDate>
            <atom:updated>2022-08-25T20:14:10.359Z</atom:updated>
            <content:encoded><![CDATA[<p>In a world full of data flooding out from every angle, sometimes, we need a fast way to process data, one of the solid pieces of new data infrastructures that has taken over the IT landscape is Apache Kafka.</p><h3>What is Apache Kafka?</h3><p>Apache Kafka is a distributed streaming platform, it has three main capabilities:<br> -Reading and writing records like a message queue<br> -Storing records with fault tolerance<br> -Processing streams as they occur</p><p>Kafka includes clients to interface with other systems. One such client type is called a producer, which sends multiple data streams to the Kafka brokers. The brokers serve a similar function as the receiver. Kafka also includes consumers and clients that can read data from the brokers and process it. Data does not have to be limited to only a single destination. The producers and consumers are completely decoupled, allowing each client to work independently.</p><p>Kafka acts as a middleman for data coming into the system and out of the system.</p><p>Kafka’s message delivery can take at least the following three delivery methods:</p><p> * At-least-once semantics — A message is sent as needed until it is acknowledged.<br> * At-most-once semantics — A message is only sent once and not resent on failure.<br> * Exactly-once semantics — A message is only seen once by the consumer of the message.</p><ul><li>At-least-once semantics: Kafka allows the producer of messages to send the same message more than once and have it written to the broker.</li><li>At-most-once semantics: When a producer of messages might send a message once, in the case of failure, the producer moves on, and does not attempt to send it again.</li><li>Exactly-once semantics: This one is ideal for many cases, it prevents duplicate messages, and assure sending the same message, and receiving the same message.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*moO0Sq5jNp7W1FwYAxUl2w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e52bc1eeeec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 main techniques to rotate an Array in Java.]]></title>
            <link>https://medium.com/@elmansouri.houssam/3-main-techniques-to-rotate-an-array-in-java-3f6b52b8bbe8?source=rss-2fdd839a62a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f6b52b8bbe8</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[El mansouri Houssam]]></dc:creator>
            <pubDate>Mon, 15 Aug 2022 14:58:26 GMT</pubDate>
            <atom:updated>2022-08-15T14:58:26.722Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we going to talk about three techniques to rotate an array that is mostly used in Java.</p><p>What is mean “Array Rotation”:<br>It means rotating an array such that elements are shifted by a specific value.</p><blockquote>for example: A[1, 2, 3, 4, 5]<br>rotate once to the left: A[2, 3, 4, 5, 1].</blockquote><blockquote>rotate once to the right: A[5, 1, 2, 3, 4]</blockquote><p>In the examples above, I have moved all elements to the next/previous position by 1 on the right or left sides.</p><p>As mentioned in the prelude of the article, there are 3 core techniques to rotate an array:</p><p>1-Block swap algorithm for array rotation<br>2-Reversal algorithm for array rotation<br>3-Juggling algorithm for array rotation</p><p>We’ll explore each technique.</p><h3>1 — Block swap algorithm for array rotation.</h3><p>The Block swap algorithm is used to rotate an array by any number of positions.</p><p>The steps of the Block Swap Algorithm are:<br>1. Divide the array into two parts, A = arr[0…d-1] and B = arr[d…n-1].<br>2. While the size of A is not equal to the size of B, do this:<br>2.1 If the size of A is smaller than B, swap A with a subarray of B of size equal to that of A and which is not adjacent to A.<br>2.2 Else(size of B is smaller than A), swap B with a subarray of A of size equal to that of A and which is not adjacent to B.<br>3. Swap A and B</p><p>Implementation of Block Swap Algorithm:</p><pre>public static void rotate(int[] arr, int i, int d, int n) {<br>    if(d == 0 || n == 0)<br>        return;<br><br>    if(d == (n - d)) {<br>        <em>swap</em>(arr, i, n - d + 1, d);<br>    }<br><br>    else if(d &lt; (n - d)) {<br>        <em>swap</em>(arr, i, n - d + 1, d);<br>        <em>rotate</em>(arr, i, d, n - d);<br>    }else<br>    {<br>        <em>swap</em>(arr, i, d, n-d);<br>        <em>rotate</em>(arr, n-d+i, 2*d - n,d);<br>    }<br>}<br><br>public static void swap(int arr[], int s, int e, int d) {<br>    for (int i = 0; i &lt; d; i++) {<br>        int temp = arr[s + i];<br>        arr[s + i] = arr[e + i];<br>        arr[e + i] = temp;<br>    }<br>}</pre><p>Time Complexity: This algorithm takes O(N) because, for each rotation, we swap d elements<br>Space Complexity: No auxiliary space is used, thereby, space complexity is O(1)</p><h3>2 — Reversal algorithm for array rotation.</h3><p>The reversal algorithm is widely used to rotate an array efficiently. it used the concept of reversing an array as a utility function.</p><p>Following is the algorithm to rotate an array by ‘d’ places:<br>1. Reverse the first d elements.<br>2. Reverse the remaining n — d elements of the array.<br>3. Reverse the entire array.</p><p>Implementations of Reversal Algorithm:</p><pre>public static void reverse(int arr[], int i, int j)<br>{<br>    int s = i, e = j;<br>    while(s &lt; e)<br>    {<br>        int temp = arr[s];<br>        arr[s] = arr[e];<br>        arr[e] = temp;<br>        s++;<br>        e--;<br>    }<br>}<br><br>public static void rotate(int arr[], int d)<br>{<br>    <em>reverse</em>(arr, 0, d-1);<br>    <em>reverse</em>(arr, d, n-1);<br>    <em>reverse</em>(arr, 0, n-1);<br>}</pre><p>Time Complexity: Reversing an array takes O(N) time, where N= number of elements to be reversed.</p><p>Hence the time complexity is O(N).</p><p>Space Complexity: This algorithm does not take any spare space, thereby, the space complexity is O(1).</p><h3>3—Juggling algorithm for array rotation.</h3><p>The final approach to rotate an array, named, Juggling Algorithm</p><p>If we need to rotate the array d times, we can do this by calling a function that rotates the array by 1 position. we simply store the first element in a temporary variable and move all the elements ahead by 1 ( arr[i-1] = arr[i] ), this function will require O(N) time and O(1) auxiliary space, if this function called d times, thus, the time complexity will become O(N * d).</p><p>Steps in the Juggling algorithm are:</p><p>1-We divide the array into GCD(n,d) parts and apply what we have mentioned above.</p><p>2-The first elements from each set are rotated. This makes the first element<br>of the set the first element of the last set. The 1st element of the 2nd set<br>becomes the first element of the first set and so on.</p><p>3-Next, the second elements are rotated in a similar fashion.</p><p>Implementation of Juggling algorithm:</p><pre>int gcd(int a, int b)<br>{<br>    if (b == 0)<br>        return a;<br>    return gcd(b, a % b);<br>}<br>void leftRotate(int arr[], int d, int n)<br>{<br>    d = d % n;<br>    int g = gcd(d, n);<br>    for (int i = 0; i &lt; g; i++)<br>    {<br>        int temp = arr[i];<br>        int j = i;<br>        while (true)<br>        {<br>            int k = j + d;<br>            if (k &gt;= n)<br>                k = k - n;<br>            if (k == i)<br>                break;<br>            arr[j] = arr[k];<br>            j = k;<br>        }<br>        arr[j] = temp;<br>    }<br>}</pre><p>Time Complexity: this algorithm takes O(N) where N is the size of the array.</p><p>Space Complexity: The juggling algorithm does not take spare space, hence the space complexity is O(1).</p><p>Thanks for your time, I wish the article would be meaningful for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f6b52b8bbe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>