<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" >
  <generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator>
  <link href="https://mouaad.aallam.com/feed.xml" rel="self" type="application/atom+xml" />
  <link href="https://mouaad.aallam.com/" rel="alternate" type="text/html" />
  <updated>2026-04-20T10:12:55+00:00</updated>
  <id>https://mouaad.aallam.com/feed.xml</id>

  
  
  

  
    <title type="html">Mouaad Aallam</title>
  

  
    <subtitle>Mouaad Aallam&apos;s personal website/blog</subtitle>
  

  

  
  
  
  
  
  
  
    <entry>
      

      <title type="html">Code execution for MCP</title>
      <link href="https://mouaad.aallam.com/code-execution-for-mcp/" rel="alternate" type="text/html" title="Code execution for MCP" />
      <published>2026-04-12T12:10:00+00:00</published>
      <updated>2026-04-12T12:10:00+00:00</updated>
      <id>https://mouaad.aallam.com/code-execution-for-mcp</id>
      
      
        <content type="html" xml:base="https://mouaad.aallam.com/code-execution-for-mcp/"><![CDATA[<p>There is a pattern showing up more often in agent systems: instead of asking the model to call one tool at a time, let it write code that calls tools, then run that code inside a controlled environment.</p>

<p>At first glance, this looks like a small implementation detail. In practice, it changes three important things:</p>

<ol>
  <li>how much context the model consumes,</li>
  <li>how intermediate data moves through the system,</li>
  <li>where the real security boundary actually lives.</li>
</ol>

<p>This post looks at the problem, the external signals that validate it, and the architecture behind <a href="https://github.com/aallam/execbox"><code class="language-plaintext highlighter-rouge">execbox</code></a> as one concrete response.</p>

<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/direct_vs_code_execution.svg" alt="Direct MCP tool calling versus code execution" width="90%" /></p>
</div>

<h2 id="problem">Problem</h2>

<p>The Model Context Protocol (MCP) made tool integration dramatically more uniform, but there is still a scaling problem once agents are connected to many tools or many servers.</p>

<p>In the naive setup, the client exposes tool definitions directly to the model, then runs a loop like:</p>

<ol>
  <li>model inspects available tools,</li>
  <li>model calls one tool,</li>
  <li>tool result is pushed back through the model context,</li>
  <li>model decides the next tool call,</li>
  <li>repeat.</li>
</ol>

<p>This works, but it has costs:</p>

<ul>
  <li>every exposed tool definition consumes context,</li>
  <li>every intermediate result flows back through the model,</li>
  <li>large payloads are copied multiple times,</li>
  <li>multi-step control flow becomes expensive and noisy,</li>
  <li>the boundary between “what the model can reason about” and “what the system should execute” stays blurry.</li>
</ul>

<p>Once you connect hundreds of tools, or even a handful of tools returning large documents or datasets, the overhead is hard to ignore.</p>

<pre class="mermaid">
flowchart LR
    M["Model"] --&gt; T["Tool catalog in context"]
    T --&gt; C1["Call tool A"]
    C1 --&gt; R1["Return result to model"]
    R1 --&gt; C2["Call tool B"]
    C2 --&gt; R2["Return another result"]
    R2 --&gt; M

    classDef model fill:#efe7ff,stroke:#6a3fd4,color:#20113a
    classDef catalog fill:#fff3d6,stroke:#d1a11f,color:#4f3200
    classDef tool fill:#d8f3ef,stroke:#1b8c7a,color:#0f3c36
    class M model
    class T catalog
    class C1,R1,C2,R2 tool
</pre>

<h2 id="signals">Signals</h2>

<p>What made this pattern feel less like a personal preference and more like a real architectural direction is that Anthropic and Cloudflare both published work pointing at the same underlying issue.</p>

<p>Anthropic’s post, <a href="https://www.anthropic.com/engineering/code-execution-with-mcp">Code execution with MCP: Building more efficient agents</a>, describes two core scaling problems with direct MCP tool usage:</p>

<ul>
  <li>tool definitions overload the context window,</li>
  <li>intermediate tool results consume additional tokens.</li>
</ul>

<p>Their proposed shift is straightforward: let the model write code against tool-like APIs, load definitions on demand, and keep intermediate processing inside the execution environment instead of replaying everything through the model.</p>

<p>Cloudflare’s post, <a href="https://blog.cloudflare.com/code-mode-mcp/">Code Mode: give agents an entire API in 1,000 tokens</a>, makes the same argument from a different angle. They describe “Code Mode” as replacing a large tool surface with a much smaller interface where the model writes code against a typed SDK, then executes that code. For their Cloudflare API MCP server, they report a fixed footprint of around 1,000 tokens and claim a <strong>99.9%</strong> reduction versus a naive full-tool exposure.</p>

<p>Then Cloudflare followed that with <a href="https://blog.cloudflare.com/dynamic-workers/">Sandboxing AI agents, 100x faster</a>, which focuses on the other half of the problem: if models are going to generate code dynamically, that code has to run somewhere safe. Their point is direct and correct: you cannot just <code class="language-plaintext highlighter-rouge">eval()</code> model-generated code in the host application and call it a day. They also argue that containers are often heavier than you want for high-volume, per-task execution.</p>

<p>Taken together, these posts point to a useful framing:</p>

<ul>
  <li>direct tool calling is often too expensive at scale,</li>
  <li>code execution is a viable way to compress planning and data movement,</li>
  <li>code execution only helps if the runtime boundary is explicit and controlled.</li>
</ul>

<p>That last point matters most here.</p>

<h2 id="constraints">Constraints</h2>

<p>Viewed through that lens, the design constraints become clearer.</p>

<p>If the model is going to write code that interacts with tools, then the system needs at least four properties:</p>

<ol>
  <li>
    <p><strong>Explicit capability exposure</strong><br />
The host must decide exactly which tools exist and under what names.</p>
  </li>
  <li>
    <p><strong>A stable execution contract</strong><br />
The model-facing surface should stay the same even if the runtime changes.</p>
  </li>
  <li>
    <p><strong>A real boundary between host and guest</strong><br />
Tool calls should cross a structured interface, not leak arbitrary host authority.</p>
  </li>
  <li>
    <p><strong>Runtime choice</strong><br />
Different deployments need different trade-offs: easiest setup, off-main-thread execution, child-process lifecycle separation, or an application-owned remote boundary.</p>
  </li>
</ol>

<p>This is where a lot of existing discussions stop. They establish that “code instead of direct tool calls” is useful, but they leave open a practical question:</p>

<p>What does the execution layer actually look like if you want to use this pattern outside one specific platform?</p>

<h2 id="implementation">Implementation</h2>

<p><a href="https://github.com/aallam/execbox"><code class="language-plaintext highlighter-rouge">execbox</code></a> is one answer to that question.</p>

<p>At a high level, it is a Node.js library for running guest JavaScript against host-defined tools and wrapped MCP servers, without hard-wiring the whole system to one runtime shape.</p>

<p>That public surface is intentionally small: <code class="language-plaintext highlighter-rouge">@execbox/core</code> owns the execution contract and MCP adapters, <code class="language-plaintext highlighter-rouge">@execbox/quickjs</code> is the default starting point, <code class="language-plaintext highlighter-rouge">@execbox/remote</code> covers application-owned transport boundaries, and <code class="language-plaintext highlighter-rouge">@execbox/isolated-vm</code> is the alternate in-process runtime. For QuickJS specifically, the runtime boundary is mostly a host-mode choice inside <code class="language-plaintext highlighter-rouge">@execbox/quickjs</code>: stay inline, move off the main thread with <code class="language-plaintext highlighter-rouge">host: "worker"</code>, or move into a child process with <code class="language-plaintext highlighter-rouge">host: "process"</code>.</p>

<p>The core model is intentionally small:</p>

<ol>
  <li>host code defines tools, or discovers them from an MCP source,</li>
  <li>those tools are resolved into a deterministic guest namespace,</li>
  <li>guest code runs against that namespace,</li>
  <li>tool calls cross a host-controlled boundary and return structured JSON-compatible results.</li>
</ol>

<p>That provides one execution contract while still letting the deployment boundary change.</p>

<h2 id="architecture">Architecture</h2>

<p>At a high level, the architecture is easier to think about in terms of boundaries than packages.</p>

<p>There are five moving parts:</p>

<ol>
  <li>the host application defines or discovers capabilities,</li>
  <li>those capabilities are resolved into a guest-facing namespace,</li>
  <li>guest code runs inside a chosen runtime,</li>
  <li>tool calls cross a controlled host boundary,</li>
  <li>results come back as structured data rather than arbitrary host objects.</li>
</ol>

<pre class="mermaid">
sequenceDiagram
    autonumber
    participant App as Host application
    participant NS as Resolved namespace
    participant Guest as Guest runtime
    participant Boundary as Host boundary
    participant Systems as Systems / APIs / MCP servers

    App-&gt;&gt;NS: Define or discover capabilities
    App-&gt;&gt;Guest: Execute code with namespace
    Guest-&gt;&gt;Boundary: Call tool
    Boundary-&gt;&gt;Systems: Invoke capability
    Systems--&gt;&gt;Boundary: Structured result
    Boundary--&gt;&gt;Guest: Return JSON-safe value
    Guest--&gt;&gt;App: Return execution result
</pre>

<p>The main design goal is that the namespace and call contract stay stable even when the runtime changes. The same model can start in-process, move off the main thread, move into a child process, or sit behind an application-owned transport without forcing a rewrite of how capabilities are exposed.</p>

<p>MCP can appear on either side of that flow:</p>

<ul>
  <li>upstream, as a source of tools that are wrapped into the guest namespace,</li>
  <li>downstream, as a surface that exposes code execution back out to MCP clients.</li>
</ul>

<p>Internally, that maps to <code class="language-plaintext highlighter-rouge">@execbox/core</code>, <code class="language-plaintext highlighter-rouge">@execbox/quickjs</code>, <code class="language-plaintext highlighter-rouge">@execbox/remote</code>, <code class="language-plaintext highlighter-rouge">@execbox/isolated-vm</code>, and the <code class="language-plaintext highlighter-rouge">@execbox/core/protocol</code> transport subpath used by hosted and remote flows. The user-facing idea is simpler: define capabilities once, start with <code class="language-plaintext highlighter-rouge">@execbox/quickjs</code>, and only move to a stronger host boundary or remote transport when the deployment actually needs it.</p>

<h2 id="usage">Usage</h2>

<p>In TypeScript, one of the cleanest ways to express that flow is to start from an MCP server declared with the MCP SDK itself, then expose it to guest code through <code class="language-plaintext highlighter-rouge">execbox</code>.</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="p">{</span> <span class="nx">McpServer</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">@modelcontextprotocol/sdk/server/mcp.js</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">openMcpToolProvider</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">@execbox/core/mcp</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">QuickJsExecutor</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">@execbox/quickjs</span><span class="dl">"</span><span class="p">;</span>
<span class="k">import</span> <span class="o">*</span> <span class="kd">as </span><span class="nx">z</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">zod</span><span class="dl">"</span><span class="p">;</span>

<span class="kd">const</span> <span class="nx">upstreamServer</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">McpServer</span><span class="p">({</span>
  <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">upstream</span><span class="dl">"</span><span class="p">,</span>
  <span class="na">version</span><span class="p">:</span> <span class="dl">"</span><span class="s2">1.0.0</span><span class="dl">"</span><span class="p">,</span>
<span class="p">});</span>

<span class="nx">upstreamServer</span><span class="p">.</span><span class="nf">registerTool</span><span class="p">(</span>
  <span class="dl">"</span><span class="s2">search-docs</span><span class="dl">"</span><span class="p">,</span>
  <span class="p">{</span>
    <span class="na">description</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Search documentation.</span><span class="dl">"</span><span class="p">,</span>
    <span class="na">inputSchema</span><span class="p">:</span> <span class="p">{</span>
      <span class="na">query</span><span class="p">:</span> <span class="nx">z</span><span class="p">.</span><span class="nf">string</span><span class="p">(),</span>
    <span class="p">},</span>
    <span class="na">outputSchema</span><span class="p">:</span> <span class="p">{</span>
      <span class="na">hits</span><span class="p">:</span> <span class="nx">z</span><span class="p">.</span><span class="nf">array</span><span class="p">(</span><span class="nx">z</span><span class="p">.</span><span class="nf">string</span><span class="p">()),</span>
    <span class="p">},</span>
  <span class="p">},</span>
  <span class="k">async </span><span class="p">(</span><span class="nx">args</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">({</span>
    <span class="na">content</span><span class="p">:</span> <span class="p">[{</span> <span class="na">text</span><span class="p">:</span> <span class="s2">`found </span><span class="p">${</span><span class="nx">args</span><span class="p">.</span><span class="nx">query</span><span class="p">}</span><span class="s2">`</span><span class="p">,</span> <span class="na">type</span><span class="p">:</span> <span class="dl">"</span><span class="s2">text</span><span class="dl">"</span> <span class="p">}],</span>
    <span class="na">structuredContent</span><span class="p">:</span> <span class="p">{</span>
      <span class="na">hits</span><span class="p">:</span> <span class="p">[</span><span class="nx">args</span><span class="p">.</span><span class="nx">query</span><span class="p">],</span>
    <span class="p">},</span>
  <span class="p">}),</span>
<span class="p">);</span>

<span class="kd">const</span> <span class="nx">handle</span> <span class="o">=</span> <span class="k">await</span> <span class="nf">openMcpToolProvider</span><span class="p">({</span> <span class="na">server</span><span class="p">:</span> <span class="nx">upstreamServer</span> <span class="p">});</span>
<span class="kd">const</span> <span class="nx">executor</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">QuickJsExecutor</span><span class="p">();</span>
<span class="kd">const</span> <span class="nx">result</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">executor</span><span class="p">.</span><span class="nf">execute</span><span class="p">(</span>
  <span class="dl">'</span><span class="s1">(await mcp.search_docs({ query: "quickjs" })).structuredContent.hits[0]</span><span class="dl">'</span><span class="p">,</span>
  <span class="p">[</span><span class="nx">handle</span><span class="p">.</span><span class="nx">provider</span><span class="p">],</span>
<span class="p">);</span>
</code></pre></div></div>

<p>This keeps the API close to the MCP TypeScript SDK itself: the server is declared once, <code class="language-plaintext highlighter-rouge">zod</code> stays the schema language, and the same server can be exposed to guest code as a callable namespace. That same shape also works with <code class="language-plaintext highlighter-rouge">new QuickJsExecutor({ host: "worker" })</code> or <code class="language-plaintext highlighter-rouge">new QuickJsExecutor({ host: "process" })</code> when you want a stronger local boundary, without changing how capabilities are declared.</p>

<h2 id="boundary">Boundary</h2>

<p>This is the most important design point in the system. The provider and tool surface is the real capability boundary.
If guest code can call a dangerous tool, guest code can exercise that authority. The runtime can make abuse harder, contain failures better, and narrow blast radius, but it does not erase the authority behind the exposed capability.</p>

<p>That is why <code class="language-plaintext highlighter-rouge">execbox</code> is explicit about what it does provide:</p>

<ul>
  <li>fresh execution state per call,</li>
  <li>JSON-only tool and result boundaries,</li>
  <li>schema validation around host tool execution,</li>
  <li>bounded logs,</li>
  <li>timeout and memory controls,</li>
  <li>abort propagation into in-flight host work.</li>
</ul>

<h2 id="why-it-matters">Why it matters</h2>

<p>Anthropic and Cloudflare helped validate the same broad pattern:</p>

<ul>
  <li>code execution can be much more context-efficient than direct tool loops,</li>
  <li>loading only the definitions you need is a better scaling model,</li>
  <li>generated code needs a proper execution boundary.</li>
</ul>

<p>What was missing in practice was a reusable layer that made those ideas portable across runtimes and MCP integration patterns instead of tying them to one agent host or one vendor platform. In practice that means you can keep one capability model, start with the simplest QuickJS setup, and then move to worker-hosted, process-hosted, or transport-backed execution without rewriting the host/tool contract.</p>

<p>That is what <a href="https://github.com/aallam/execbox"><code class="language-plaintext highlighter-rouge">execbox</code></a> is for.</p>

<p>If you want to look at the implementation:</p>

<ul>
  <li><a href="https://execbox.aallam.com/getting-started">Getting Started</a></li>
  <li><a href="https://execbox.aallam.com/examples">Examples</a></li>
  <li><a href="https://execbox.aallam.com/architecture/">Architecture</a></li>
  <li><a href="https://execbox.aallam.com/security">Security</a></li>
  <li><a href="https://github.com/aallam/execbox">GitHub repository</a></li>
</ul>]]></content>
      

      
      
      
      
      

      <author>
        <name></name>
        
        
      </author>

      
        
      

      
        <category term="MCP" />
      
        <category term="AI Agents" />
      
        <category term="Architecture" />
      

      
      
        <summary type="html"><![CDATA[Why code execution can scale MCP agents better than direct tool loops, while keeping execution boundaries clearer.]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mouaad.aallam.com/assets/images/generated/posts/2026-04-12-code-execution-for-mcp.png" />
        <media:content medium="image" url="https://mouaad.aallam.com/assets/images/generated/posts/2026-04-12-code-execution-for-mcp.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
    <entry>
      

      <title type="html">Java Memory Model</title>
      <link href="https://mouaad.aallam.com/java-memory-model/" rel="alternate" type="text/html" title="Java Memory Model" />
      <published>2019-08-24T14:42:00+00:00</published>
      <updated>2019-08-24T14:42:00+00:00</updated>
      <id>https://mouaad.aallam.com/java-memory-model</id>
      
      
        <content type="html" xml:base="https://mouaad.aallam.com/java-memory-model/"><![CDATA[<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/cart-observing-wrong.png" alt="Java" width="50%" /></p>
</div>

<h2 id="the-problem">The problem</h2>

<p>In Java, a program code can change a lot between its Java source code form, Byte code form, and machine code form. The
Java source code focuses more on <em>readability and clarity</em>, while the machine code focuses on <em>performance and
efficiency</em>. The JVM is allowed to optimize the code, with different degrees of optimization (depending on the
compilation stage), as long as it remains correct. But, this task can be handy in the context of multi-threaded
applications.</p>

<h3 id="sequential-consistency">Sequential consistency</h3>

<p>There are multiple levels of caching while executing a program; the processor never operates on values directly in the
main memory, but instead, it loads the values to its cache, manipulates them, then writes them back to the main memory.
Let’s take the following example:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Reorder</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">foo</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
    <span class="kt">int</span> <span class="n">bar</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">calc</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">foo</span> <span class="o">+=</span> <span class="mi">1</span><span class="o">;</span> <span class="c1">//#1</span>
        <span class="n">bar</span> <span class="o">+=</span> <span class="mi">1</span><span class="o">;</span> <span class="c1">//#2</span>
        <span class="n">foo</span> <span class="o">+=</span> <span class="mi">2</span><span class="o">;</span> <span class="c1">//#3</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>How the processor can execute the method <code class="language-plaintext highlighter-rouge">calc()</code> in memory?</p>

<ol>
  <li>Load <code class="language-plaintext highlighter-rouge">foo</code> from main memory to processor cache. Increment by 1, write it back the main memory (<code class="language-plaintext highlighter-rouge">#1</code>).</li>
  <li>Load <code class="language-plaintext highlighter-rouge">bar</code> from main memory to processor cache. Increment by 1, write it back the main memory (<code class="language-plaintext highlighter-rouge">#2</code>).</li>
  <li>Load <code class="language-plaintext highlighter-rouge">foo</code> from main memory to processor cache. Increment by 2, write it back the main memory (<code class="language-plaintext highlighter-rouge">#3</code>).</li>
</ol>

<p>How the earlier example can be optimized ? by swapping the instructions (<code class="language-plaintext highlighter-rouge">#2</code> and <code class="language-plaintext highlighter-rouge">#3</code>):</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">calc</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">foo</span><span class="o">+=</span><span class="mi">1</span><span class="o">;</span> <span class="c1">//#1</span>
    <span class="n">foo</span><span class="o">+=</span><span class="mi">2</span><span class="o">;</span> <span class="c1">//#3</span>
    <span class="n">bar</span><span class="o">+=</span><span class="mi">1</span><span class="o">;</span> <span class="c1">//#2</span>
<span class="o">}</span>
</code></pre></div></div>

<ol>
  <li>Load <code class="language-plaintext highlighter-rouge">foo</code> from main memory to processor cache. Increment by 1, Increment by 2, write it back the main memory (<code class="language-plaintext highlighter-rouge">#1</code>
and <code class="language-plaintext highlighter-rouge">#3</code>).</li>
  <li>Load <code class="language-plaintext highlighter-rouge">bar</code> from main memory to processor cache. Increment by 1, write it back the main memory (<code class="language-plaintext highlighter-rouge">#2</code>).</li>
</ol>

<p>In a single-threaded program, this optimization can be considered without side effects, however, in a multi-threaded
world, it introduces some abnormal behavior:</p>

<p>The possible values of the variables overtime in the two cases shows the slight difference:</p>

<ul>
  <li>Before optimisation:
    <ol>
      <li>(foo == 0, bar == 0)</li>
      <li>(foo == 1, bar == 0)</li>
      <li><strong>(foo == 1, bar == 1)</strong></li>
      <li>(foo == 3, bar == 1)</li>
    </ol>
  </li>
  <li>After optimisation:
    <ol>
      <li>(foo == 0, bar == 0)</li>
      <li>(foo == 1, bar == 0)</li>
      <li><strong>(foo == 3, bar == 0)</strong></li>
      <li>(foo == 3, bar == 1)</li>
    </ol>
  </li>
</ul>

<p>This previous example is an optimization that the JVM is allowed to do. The JVM can do much more complex optimizations,
however, the outcome might be unexpected in a multi-threaded world! But why optimize then? The answer: <em>memory access
latency</em>!</p>
<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/latency_numbers.png" alt="latency numbers" /></p>
</div>

<h3 id="eventual-consistency">Eventual consistency</h3>

<p>A machine can have multiprocessors, and (at some level) each processor has its cache, which means, each processor loads
only the values it needs for its operations.
Let’s say we have two processors and the following program:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Caching</span> <span class="o">{</span>
    <span class="kt">boolean</span> <span class="n">flag</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>
    <span class="kt">int</span> <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">thread1</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">while</span> <span class="o">(</span><span class="n">flag</span><span class="o">)</span> <span class="n">count</span><span class="o">++;</span>
    <span class="o">}</span>

    <span class="kt">void</span> <span class="nf">thread2</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">flag</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span> 
</code></pre></div></div>

<p>Let’s say processor <code class="language-plaintext highlighter-rouge">#1</code> will run the method <code class="language-plaintext highlighter-rouge">thread1()</code> and processor <code class="language-plaintext highlighter-rouge">#2</code> will run the method <code class="language-plaintext highlighter-rouge">thread2()</code>. An
optimization can be the following:</p>

<ul>
  <li>Since <code class="language-plaintext highlighter-rouge">thread1()</code> never modifies the <code class="language-plaintext highlighter-rouge">flag</code> variable, there is no need to load it from the main memory for each loop
check, only once to the cache is enough -&gt; the changes to <code class="language-plaintext highlighter-rouge">flag</code> might never be observed!</li>
  <li>Processor <code class="language-plaintext highlighter-rouge">#2</code> has no obligation to write it changes to the <code class="language-plaintext highlighter-rouge">flag</code> variable to the main memory! This means an
optimization can be to simply not do the operation at all!</li>
</ul>

<h3 id="13-atomicity">1.3 Atomicity</h3>

<p>The atomicity in Java is to consider all values are atomic, which means that the modification to a variable (for example
64 bit types like <code class="language-plaintext highlighter-rouge">long</code>  and <code class="language-plaintext highlighter-rouge">double</code>) to be done atomically.</p>

<p>Let’s consider the following example:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">LongTearing</span> <span class="o">{</span>
    <span class="kt">long</span> <span class="n">foo</span> <span class="o">=</span> <span class="mi">0L</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">thread1</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">foo</span> <span class="o">=</span> <span class="mh">0x0000FFFF</span><span class="o">;</span> <span class="c1">// 2147483647 </span>
    <span class="o">}</span>

    <span class="kt">void</span> <span class="nf">thread2</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">foo</span> <span class="o">=</span> <span class="mh">0xFFFF0000</span><span class="o">;</span> <span class="c1">// -2147483648 </span>
    <span class="o">}</span>
<span class="o">}</span> 
</code></pre></div></div>

<p>A 64 bit <code class="language-plaintext highlighter-rouge">long</code> variable, is written in two slots in the case of 32 memory, a problem can occur here:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">thread1()</code> writes the <em>first half</em> of its value to memory <code class="language-plaintext highlighter-rouge">0000</code>.</li>
  <li><code class="language-plaintext highlighter-rouge">thread2()</code> writes the <em>second half</em> of its value to memory <code class="language-plaintext highlighter-rouge">0000</code>.</li>
  <li><code class="language-plaintext highlighter-rouge">thread1()</code> writes the <em>second half</em> of its value to memory <code class="language-plaintext highlighter-rouge">FFFF</code>.</li>
  <li><code class="language-plaintext highlighter-rouge">thread1()</code> writes the <em>first half</em> of its value to memory <code class="language-plaintext highlighter-rouge">FFFF</code>.</li>
  <li>The final value of the variable will be then: <code class="language-plaintext highlighter-rouge">0xFFFFFFFF</code> !!!</li>
</ul>

<h3 id="processor-optimization">Processor optimization</h3>

<p>Ordering operations sometimes are tied to the processor architecture. Optimization needs can be different for example
between ARM processors and x86 processors. ARM processors can be more aggressive because they are designed for
energy-consuming efficiency, than x86 processors which are more about calculation speed.</p>

<h2 id="what-is-the-java-memory-model">What is the Java memory model?</h2>

<p>Java memory model answers the question: what values can be observed upon reading from a specific field?</p>

<p>Formally specified by breaking down a Java program into <strong>actions</strong> and applying several <strong>orderings</strong> to these actions.
If one can derive a so-called <strong>happens-before</strong> ordering between a <strong>write action</strong> and a <strong>read action</strong> of one
field, the Java memory model guarantees that the read returns a particular value.</p>

<p>The Java memory machine guarantees <em>intra-thread consistency</em> equivalent to sequential consistency.</p>

<h3 id="building-blocks">Building blocks</h3>

<p>According to the Java memory model, using the following keywords, a programmer can indicate to the JVM to <em>refrain from
optimizations</em> that could otherwise cause concurrency issues:</p>

<ul>
  <li>Field-scoped: <code class="language-plaintext highlighter-rouge">final</code>, <code class="language-plaintext highlighter-rouge">volatile</code>.</li>
  <li>Method-scoped: <code class="language-plaintext highlighter-rouge">synchronized</code> (method/block), <code class="language-plaintext highlighter-rouge">java.util.concurrent .*</code>.</li>
</ul>

<p>In terms of the Java memory model, the above concepts introduce additional <strong>synchronization actions</strong> which introduce
additional (partial) <strong>orders</strong>. Without such modifiers, reads and writes might not be ordered what results in a data
race.<br />
A memory model is a <strong>trade-off</strong> between a language’s simplicity (consistency/atomicity) and its performance.</p>

<h3 id="volatile">Volatile</h3>

<p>Let’s take the following example:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">DataRace</span> <span class="o">{</span>
    <span class="kt">boolean</span> <span class="n">ready</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span>
    <span class="kt">int</span> <span class="n">answer</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">thread1</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">while</span> <span class="o">(!</span><span class="n">ready</span><span class="o">)</span> <span class="o">;</span>
        <span class="k">assert</span> <span class="n">answer</span> <span class="o">==</span> <span class="mi">42</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kt">void</span> <span class="nf">thread2</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">answer</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>   <span class="c1">// #1</span>
        <span class="n">ready</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>  <span class="c1">// #2</span>
    <span class="o">}</span>
<span class="o">}</span> 
</code></pre></div></div>

<p>The lines <code class="language-plaintext highlighter-rouge">#1</code> and <code class="language-plaintext highlighter-rouge">#2</code> can be reordered! This means, the assertion in method <code class="language-plaintext highlighter-rouge">thread1()</code> can fail in a multi-threaded
world!<br />
A solution ? The keyword <code class="language-plaintext highlighter-rouge">volatile</code>:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">DataRace</span> <span class="o">{</span>
    <span class="kd">volatile</span> <span class="kt">boolean</span> <span class="n">ready</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span>
    <span class="kt">int</span> <span class="n">answer</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">thread1</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">while</span> <span class="o">(!</span><span class="n">ready</span><span class="o">)</span> <span class="o">;</span>
        <span class="k">assert</span> <span class="n">answer</span> <span class="o">==</span> <span class="mi">42</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kt">void</span> <span class="nf">thread2</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">answer</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>   <span class="c1">// #1</span>
        <span class="n">ready</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>  <span class="c1">// #2</span>
    <span class="o">}</span>
<span class="o">}</span> 
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">volatile</code> implies for two threads with a write-read relationship on the <em>*same field*</em>, certain optimizations are not
allowed!</p>

<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/volatile_sync.png" alt="Volatile Synchronization" /></p>
</div>

<ol>
  <li>When a thread <em>writes</em> to a <code class="language-plaintext highlighter-rouge">volatile</code> variable, all of its previous writes are <em>guaranteed</em> to be visible to another
thread when that thread is reading the same value.</li>
  <li>Both threads <em>must align</em> “their” <code class="language-plaintext highlighter-rouge">volatile</code> value with that <em>in main memory</em> (flush).</li>
  <li>If the <code class="language-plaintext highlighter-rouge">volatile</code> value was a <code class="language-plaintext highlighter-rouge">long</code> or a <code class="language-plaintext highlighter-rouge">double</code> value, <em>word-tearing</em> was <em>forbidden</em>.</li>
</ol>

<h3 id="synchronized">Synchronized</h3>

<p>Another way to achieve the synchronization is by using: <code class="language-plaintext highlighter-rouge">synchronized</code>
Let’s check the following example assuming the second thread acquires the lock first:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">DataRace</span> <span class="o">{</span>
    <span class="kt">boolean</span> <span class="n">ready</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span>
    <span class="kt">int</span> <span class="n">answer</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

    <span class="kd">synchronized</span> <span class="kt">void</span> <span class="nf">thread1</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">while</span> <span class="o">(!</span><span class="n">ready</span><span class="o">)</span> <span class="o">;</span>
        <span class="k">assert</span> <span class="n">answer</span> <span class="o">==</span> <span class="mi">42</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">synchronized</span> <span class="kt">void</span> <span class="nf">thread2</span><span class="o">()</span> <span class="o">{</span> <span class="c1">//Assuming this is called 1st</span>
        <span class="n">answer</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>
        <span class="n">ready</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span> 
</code></pre></div></div>

<p>When a thread <em>releases</em> a monitor, all of its previous writes are <em>guaranteed</em> to be visible to another thread after
that thread is <em>locking the same monitor.</em>. This only applies for two threads with an <em>*unlock-lock relationship*</em> on
the same monitor!</p>
<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/synchronized_sync.png" alt="Synchronized Synchronization" /></p>
</div>

<h3 id="thread-life-cycle-semantics">Thread life-cycle semantics</h3>

<p>When a thread starts another thread, the started thread is guaranteed to see all values that were set by the starting
thread.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">ThreadLifeCycle</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">foo</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">method</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">foo</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>
        <span class="k">new</span> <span class="nf">Thread</span><span class="o">()</span> <span class="o">{</span>
            <span class="nd">@Override</span>
            <span class="kd">public</span> <span class="kt">void</span> <span class="nf">run</span><span class="o">()</span> <span class="o">{</span>
                <span class="k">assert</span> <span class="n">foo</span> <span class="o">==</span> <span class="mi">42</span><span class="o">;</span>
            <span class="o">}</span>
        <span class="o">}.</span><span class="na">start</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span> 
</code></pre></div></div>

<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/thread_lifecycle.png" alt="Thread Life-cycle" /></p>
</div>
<p>Similarly, a thread that joins another thread is guaranteed to see all values that were set by the joined thread.</p>

<h3 id="final-field-semantics">Final field semantics</h3>

<p>When a thread creates an instance, the instance’s <code class="language-plaintext highlighter-rouge">final</code> fields are <em>frozen</em>. The Java memory model requires a field’s
initial value to be visible in the initialized form to other threads.</p>
<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/freeze.png" alt="Final Synchronization" /></p>
</div>
<p>This requirement also holds for properties that are dereferenced via a <code class="language-plaintext highlighter-rouge">final</code> field, even if the field value’s properties are not final themselves (memory-chain order).</p>

<h3 id="external-actions">External actions</h3>

<p>A JIT-compiler <em>cannot</em> determine the side-effects of a <em>native</em> operation. Therefore, external actions are <em>guaranteed</em>
to <em>not be reordered</em>.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Externalization</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">foo</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">method</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">foo</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>
        <span class="n">jni</span><span class="o">();</span> <span class="c1">// Not re-ordered</span>
    <span class="o">}</span>

    <span class="kd">native</span> <span class="kt">void</span> <span class="nf">jni</span><span class="o">();</span>
<span class="o">}</span> 
</code></pre></div></div>

<p>External actions include JNI, socket communication, file system operations, or interaction with the console (
non-exclusive list).</p>

<h3 id="thread-divergence-actions">Thread-divergence actions</h3>

<p>Thread-divergence actions are <em>guaranteed to not be reordered</em>. This prevents surprising outcomes of actions that might
never be reached.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">ThreadDivergence</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">foo</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">thread1</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">while</span> <span class="o">(</span><span class="kc">true</span><span class="o">)</span> <span class="o">;</span>
        <span class="n">foo</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span> <span class="c1">// Not re-ordered</span>
    <span class="o">}</span>

    <span class="kt">void</span> <span class="nf">thread2</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">assert</span> <span class="n">foo</span> <span class="o">==</span> <span class="mi">42</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span> 
</code></pre></div></div>

<p>In the previous example, in the method <code class="language-plaintext highlighter-rouge">thread1()</code> the line <code class="language-plaintext highlighter-rouge">foo = 0</code> is unreachable. Thus not re-ordered.</p>

<h2 id="in-practice">In Practice</h2>

<p>The following are some practical examples of Java Memory Model use (or misuse).</p>

<h3 id="double-checking">Double-checking</h3>

<p>The following is a lazy instance creation example:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">DoubleChecked</span> <span class="o">{</span>
    <span class="kd">static</span> <span class="kd">volatile</span> <span class="nc">DoubleChecked</span> <span class="n">instance</span><span class="o">;</span>

    <span class="kd">static</span> <span class="nc">DoubleChecked</span> <span class="nf">getInstance</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">instance</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
            <span class="kd">synchronized</span> <span class="o">(</span><span class="nc">DoubleChecked</span><span class="o">.</span><span class="na">class</span><span class="o">)</span> <span class="o">{</span>
                <span class="k">if</span> <span class="o">(</span><span class="n">instance</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
                    <span class="n">instance</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DoubleChecked</span><span class="o">();</span>
                <span class="o">}</span>
            <span class="o">}</span>
        <span class="o">}</span>
        <span class="k">return</span> <span class="n">instance</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kt">int</span> <span class="n">foo</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

    <span class="nc">DoubleChecked</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">foo</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kt">void</span> <span class="nf">method</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">assert</span> <span class="n">foo</span> <span class="o">==</span> <span class="mi">42</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span> 
</code></pre></div></div>

<p>This example works because of <code class="language-plaintext highlighter-rouge">volatile</code>, omitting it may cause having an instance of an object created, but
uninitialized!</p>

<h3 id="arrays">Arrays</h3>

<p>Declaring an array to be <code class="language-plaintext highlighter-rouge">volatile</code> <em>does not</em> make its elements <code class="language-plaintext highlighter-rouge">volatile</code>! In the following example, there is no
write-read edge because the array is only read by any thread:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">DataRace</span> <span class="o">{</span>
    <span class="kd">volatile</span> <span class="kt">boolean</span><span class="o">[]</span> <span class="n">ready</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">boolean</span><span class="o">[]{</span><span class="kc">false</span><span class="o">};</span>
    <span class="kt">int</span> <span class="n">answer</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">thread1</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">while</span> <span class="o">(!</span><span class="n">ready</span><span class="o">[</span><span class="mi">0</span><span class="o">])</span> <span class="o">;</span>
        <span class="k">assert</span> <span class="n">answer</span> <span class="o">==</span> <span class="mi">42</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kt">void</span> <span class="nf">thread2</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">answer</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>
        <span class="n">ready</span><span class="o">[</span><span class="mi">0</span><span class="o">]</span> <span class="o">=</span> <span class="kc">true</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span> 
</code></pre></div></div>

<p>For such volatile element access: <code class="language-plaintext highlighter-rouge">java.util.concurrent.atomic.AtomicIntegerArray</code>.</p>

<h2 id="sources">Sources</h2>

<ul>
  <li><a href="https://en.wikipedia.org/wiki/Java_memory_model">Java memory model - Wikipedia</a></li>
  <li><a href="https://download.oracle.com/otndocs/jcp/memory_model-1.0-pfd-spec-oth-JSpec/">JSR-133 Java Memory Model and Thread Specification 1.0 Proposed Final Draft</a></li>
  <li><a href="https://en.wikipedia.org/wiki/Happened-before">Happened-before - Wikipedia</a></li>
  <li><a href="http://tutorials.jenkov.com/java-concurrency/java-memory-model.html">Java Memory Model - jenkov</a></li>
  <li><a href="https://www.youtube.com/watch?v=XgiXKPEILoc">The Java Memory Model for Practitioners</a></li>
  <li><a href="https://shipilev.net/blog/2016/close-encounters-of-jmm-kind/">Close Encounters of The Java Memory Model Kind</a></li>
</ul>]]></content>
      

      
      
      
      
      

      <author>
        <name></name>
        
        
      </author>

      
        
      

      
        <category term="Java" />
      
        <category term="JVM" />
      

      
      
        <summary type="html"><![CDATA[Deep dive into Java Memory Model covering sequential consistency, happens-before relationships, volatile, synchronized, and concurrency optimization patterns.]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mouaad.aallam.com/assets/images/blog/cart-observing-wrong.png" />
        <media:content medium="image" url="https://mouaad.aallam.com/assets/images/blog/cart-observing-wrong.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
    <entry>
      

      <title type="html">JVM Architecture</title>
      <link href="https://mouaad.aallam.com/java-virtual-machine-architecture/" rel="alternate" type="text/html" title="JVM Architecture" />
      <published>2019-08-08T16:16:00+00:00</published>
      <updated>2019-08-08T16:16:00+00:00</updated>
      <id>https://mouaad.aallam.com/java-virtual-machine-architecture</id>
      
      
        <content type="html" xml:base="https://mouaad.aallam.com/java-virtual-machine-architecture/"><![CDATA[<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/JVM.png" alt="Java" width="50%" /></p>
</div>

<p>Java source codes are compiled into an intermediate state called <strong>bytecode</strong> (i.e. <strong>.class</strong> file) using the Java compiler (<strong>javac</strong>). The Java Virtual Machine a.k.a <strong>JVM</strong> interprets the bytecode (without further recompilations) into native machine language. Therefore, bytecode acts as a <strong>platform-independent</strong> intermediary state which is <strong>portable</strong> among any JVM regardless of underlying OS and hardware architecture.</p>

<p><em><strong>The JVM is a specification</strong></em>. Vendors are free to customize, innovate, and improve its performance during the implementation.</p>

<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/JVM_Architecture.png" alt="JVM Architecture" width="75%" /></p>
  <figcaption class="caption">Java Virtual Machine Architecture</figcaption>
</div>

<h2 id="1-class-loader-subsystem">1. Class Loader Subsystem</h2>
<p>The <strong>JVM resides on the RAM</strong>. During execution, using the Class Loader subsystem, the class files are brought on to the RAM. This is called Java’s <strong>dynamic class loading</strong> functionality. It loads, links, and initializes the class file (<code class="language-plaintext highlighter-rouge">.class</code>) when it refers to a class for the first time at runtime (not compile time).</p>

<h3 id="11-loading">1.1. Loading</h3>
<ul>
  <li><strong>Bootstrap Class Loader</strong> loads standard JDK classes such as core Java API classes (e.g. <code class="language-plaintext highlighter-rouge">java.lang.*</code> package classes) from <code class="language-plaintext highlighter-rouge">$JAVA_HOME/jre/rt.jar</code>. The class loader acts as parent of all class loaders in Java;</li>
  <li><strong>Extension Class Loader</strong> delegates class loading request to its parent, Bootstrap and if unsuccessful, loads classes from the extensions directories (e.g. security extension functions) in extension path  <code class="language-plaintext highlighter-rouge">$JAVA_HOME/jre/lib/ext</code> or any other directory specified by the <code class="language-plaintext highlighter-rouge">java.ext.dirs</code> system property;</li>
  <li><strong>System/Application Class Loader</strong> loads application specific classes from system class path, that can be set while invoking a program using <code class="language-plaintext highlighter-rouge">-cp</code> or <code class="language-plaintext highlighter-rouge">-classpath</code> command line options.</li>
</ul>

<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/java_class_loaders.png" alt="Java Class Loaders" /></p>
</div>

<p>Note: It is possible to directly create a <em>User-defined Class Loader</em> on the code itself.</p>

<h3 id="12-linking">1.2. Linking</h3>
<p>Linking is to verify and prepare a loaded class or interface, its direct superclasses and superinterfaces, and its element type as necessary, while following the below properties:</p>

<ul>
  <li><strong>Verification</strong>: ensure the correctness of <code class="language-plaintext highlighter-rouge">.class</code> file, If verification fails, it throws runtime errors (<code class="language-plaintext highlighter-rouge">java.lang.VerifyError</code>). For instance, the following checks are performed:
    <ul>
      <li>consistent and correctly formatted symbol table;</li>
      <li>final methods / classes not overridden;</li>
      <li>methods respect access control keywords;</li>
      <li>methods have correct number and type of parameters;</li>
      <li>bytecode doesn’t manipulate stack incorrectly;</li>
      <li>variables are initialized before being read;</li>
      <li>variables are a value of the correct type.</li>
    </ul>
  </li>
  <li><strong>Preparation</strong>: allocate memory for static storage and any data structures used by the JVM such as method tables. Static fields are created and initialized to their default values, however, no initializers or code is executed at this stage;</li>
  <li><strong>Resolution</strong>: replace symbolic references from the type with direct references. It is done by searching into method area to locate the referenced entity.</li>
</ul>

<h3 id="13-initialization">1.3. Initialization</h3>
<p>The initialization logic of each loaded class or interface will be executed (e.g. calling the constructor of a class). Since JVM is multi-threaded, initialization of a class or interface should happen very carefully (i.e. make it <strong>thread safe</strong>).</p>

<h2 id="2-runtime-data-areas">2. Runtime Data Areas</h2>
<p>Runtime Data Areas are the memory areas assigned when the JVM program runs on the OS.<br />
In addition to reading <code class="language-plaintext highlighter-rouge">.class</code> files, the Class Loader subsystem generates corresponding binary data and save the following information in the Method area for each class separately:</p>
<ul>
  <li>fully qualified class name (FQCN) of the loaded class and its immediate parent class;</li>
  <li>whether <code class="language-plaintext highlighter-rouge">.class</code> file is related to a Class, Interface or Enum;</li>
  <li>modifiers, static variables, and method information etc.</li>
</ul>

<p>For every loaded <code class="language-plaintext highlighter-rouge">.class</code> file, it creates exactly one <strong>Class</strong> object to represent the file in the Heap memory. This <strong>Class</strong> object can be used to read class level information (class name, parent name, methods, variable information, static variables etc.) later in the code.</p>

<h3 id="21-method-area-shared">2.1 Method Area (Shared)</h3>
<p>This is a <em><strong>shared resource</strong></em> (only 1 method area per JVM). All JVM threads share this same method area, which means the access to the method data and the process of dynamic linking must be <strong>thread safe</strong>.<br />
Method area stores <strong>class level data</strong> (including <strong>static variables</strong>) such as:</p>
<ul>
  <li>ClassLoader reference;</li>
  <li>runtime constant pool;</li>
  <li>field data;</li>
  <li>method data;</li>
  <li>method code.</li>
</ul>

<h3 id="22-heap-area-shared">2.2 Heap Area (Shared)</h3>
<p>This is also a <strong>shared resource</strong> (only 1 heap area per JVM). Information of all <strong>objects</strong> and their corresponding <strong>instance variables and arrays</strong> are stored in the Heap area. Heap area is a great target for GC.</p>

<h3 id="23-stack-area-per-thread">2.3. Stack Area (Per thread)</h3>
<p>This is not a shared resource <em>(thread safe)</em>. Every JVM thread has a separate <strong>runtime stack</strong> to store <strong>method calls</strong>. For every such method call, one entry will be created and added (pushed) into the top of runtime stack and such entry it is called a <strong>Stack Frame</strong>.</p>

<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/JVM_stack_configuration.png" alt="JVM Stack Configuration" /></p>
</div>

<p>A Stack Frame is divided into three sub-entities:</p>
<ul>
  <li><strong>Local Variable Array</strong>: contains local variables and their values;</li>
  <li><strong>Operand Stack</strong>: this acts as a runtime workspace to perform any intermediate operation. Each method exchanges data between the Operand stack and the local variable array, and pushes or pops other method invoke results;</li>
  <li><strong>Frame Data</strong>: all symbols related to the method are stored here. For exceptions, the catch block information will also be maintained in the frame data.</li>
</ul>

<p>The frame is removed (popped) when the method returns normally or if an uncaught exception is thrown during the method invocation.
Since these are runtime stack frames, after a thread terminates, its stack frame will also be destroyed by JVM.</p>

<p>The stack frame is size fixed, however, the stack itself can be a dynamic or fixed size. If a thread requires a larger stack than allowed a <code class="language-plaintext highlighter-rouge">StackOverflowError</code> is thrown. If a thread requires a new frame and there isn’t enough memory to allocate it then an <code class="language-plaintext highlighter-rouge">OutOfMemoryError</code> is thrown.</p>

<h3 id="24-pc-registers--per-thread">2.4. PC Registers  (Per thread)</h3>
<p>For each JVM thread, when the thread starts, a separate PC (<em>Program Counter</em>) Register gets created in order to hold the address of currently-executing instruction (memory address in the method area). If the current method is native then the PC is undefined. Once the execution finishes, the PC register gets updated with the address of next instruction.</p>

<h3 id="25-native-method-stack-per-thread">2.5. Native Method Stack (Per thread)</h3>
<p>There is a direct mapping between a Java thread and a native operating system thread. After preparing all the state for a Java thread, a separate native stack also gets created in order to store native method information invoked through JNI (Java Native Interface).</p>

<p>Once the native thread has been created and initialized, it invokes the <code class="language-plaintext highlighter-rouge">run()</code> method in the Java thread. When the thread terminates, all resources for both the native and Java threads are released.
The native thread is reclaimed once the Java thread terminates. The operating system is therefore responsible for scheduling all threads and dispatching them to any available CPU.</p>

<h2 id="3-execution-engine">3. Execution Engine</h2>
<p>Execution Engine executes the instructions in the bytecode line-by-line by reading the data assigned to Runtime Data Areas.</p>

<h3 id="31-interpreter">3.1. Interpreter</h3>
<p>The interpreter <em>interprets</em> the <em>bytecode</em> and executes the instructions one-by-one. Hence, it can interpret one bytecode line quickly, but executing the interpreted result is a slower task. The disadvantage is that when one method is called multiple times, each time a new interpretation and a slower execution are required.</p>

<h3 id="32-just-in-time-jit-compiler">3.2. Just-In-Time (JIT) Compiler</h3>
<p>The JIT compiler, compiles the bytecode to native code. Then for repeated method calls, it directly provides the native code.</p>

<p>However, even for JIT compiler, it takes more time for compiling than for the interpreter to interpret. For a code segment that executes just once, it is better to interpret it instead of compiling. Also the native code is stored in the cache, which is an expensive resource. With these circumstances, JIT compiler internally checks the frequency of each method call and decides to compile each only when the selected method has occurred more than a certain level of times. This idea of <strong>adaptive compiling</strong> has been used in Oracle Hotspot VMs.</p>

<p>Execution Engine qualifies to become a key subsystem when introducing performance optimizations by JVM vendors. Among such efforts, the following 4 components can largely improve its performance:</p>
<ul>
  <li><strong>Intermediate Code Generator</strong> produces <strong>intermediate code</strong>;</li>
  <li><strong>Code Optimizer</strong> is responsible for optimizing the intermediate code generated;</li>
  <li><strong>Target Code Generator</strong> is responsible for generating <strong>Native Code</strong> (i.e.<strong>Machine Code</strong>);</li>
  <li><strong>Profiler</strong> is a special component, responsible for finding performance bottlenecks a.k.a.<strong>hotspots</strong>.</li>
</ul>

<h3 id="33-garbage-collector">3.3. Garbage Collector</h3>
<p>As long as an object is being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not reachable by the application code, the garbage collector removes it and reclaims the unused memory.</p>

<h2 id="4-java-native-interface-jni">4. Java Native Interface (JNI)</h2>
<p>This interface is used to interact with Native Method Libraries. This enables JVM to call C/C++ libraries and to be called by C/C++ libraries which may be specific to hardware.</p>

<h2 id="5-native-method-libraries">5. Native Method Libraries</h2>
<p>This is a collection of C/C++ Native Libraries which is required for the Execution Engine and can be accessed through the provided Native Interface.</p>

<h2 id="6-jvm-threads">6. JVM Threads</h2>
<p>The JVM concurrently runs multiple threads, some of these threads carry the programming logic and are created by the program (<strong>application threads</strong>), while the rest is created by JVM itself to undertake background tasks in the system (<strong>system threads</strong>).</p>

<p>The major application thread is the <strong>main thread</strong> which is created as part of invoking <code class="language-plaintext highlighter-rouge">public static void main(String[])</code> and all other application threads are created by this main thread. Application threads perform tasks such as executing instructions starting with <code class="language-plaintext highlighter-rouge">main()</code> method, creating objects in Heap area if it finds <code class="language-plaintext highlighter-rouge">new</code> keyword in any method logic etc.</p>

<p>The major system threads are as follows:</p>
<ul>
  <li><strong>Compiler threads</strong>: At runtime, compilation of bytecode to native code is undertaken by these threads;</li>
  <li><strong>GC threads</strong>: All the GC related activities are carried out by these threads;</li>
  <li><strong>Periodic task thread</strong>: The timer events (i.e. interrupts) to schedule execution of periodic operations are performed by this thread;</li>
  <li><strong>Signal dispatcher thread</strong>: This thread receives signals sent to the JVM process and handle them inside the JVM by calling the appropriate JVM methods;</li>
  <li><strong>VM thread</strong>: This thread waits for operations to appear that require the JVM to reach a safe-point where modifications to the heap can not occur. The type of operations performed by this thread are “stop-the-world” garbage collections, thread stack dumps, thread suspension and biased locking revocation.</li>
</ul>

<h2 id="7-conclusion">7. Conclusion</h2>
<p>Java is considered as both compiled (high-level java code into bytecode) and interpreted (bytecode into native machine code). By design, Java is slow due to dynamic linking and run-time interpreting, however, JIT compiler compensate for the disadvantages of the interpreter for repeating operations by keeping a native code instead of bytecode.</p>

<h2 id="8-useful-commands">8. Useful Commands</h2>
<ul>
  <li><code class="language-plaintext highlighter-rouge">javac</code>: Java compiler;</li>
  <li><code class="language-plaintext highlighter-rouge">javap</code>: Dump <code class="language-plaintext highlighter-rouge">.class</code> data;</li>
  <li><code class="language-plaintext highlighter-rouge">-XX:+PrintCompilation</code>: Log every time a method is compiled to native code;</li>
  <li><code class="language-plaintext highlighter-rouge">-XX:+PrintInlining</code>: Display a tree how methods has been inlined;</li>
  <li><code class="language-plaintext highlighter-rouge">-XX:+PrintAssembly</code>: Look at the native code that JVM is outputting;</li>
  <li><code class="language-plaintext highlighter-rouge">jps</code>: lists running  Java processes;</li>
  <li><code class="language-plaintext highlighter-rouge">jcmd</code>: used to send diagnostic command requests to the JVM
    <ul>
      <li><code class="language-plaintext highlighter-rouge">jcmd</code> (without any parameters): list all JVM processes;</li>
      <li><code class="language-plaintext highlighter-rouge">jcmd [PID] help</code>: show available commands;</li>
      <li><code class="language-plaintext highlighter-rouge">jcmd [PID] GC.heap_dump [PATH]</code>: heap dump;</li>
      <li><code class="language-plaintext highlighter-rouge">jcmd [PID] Thread.print</code>: Thread dump.</li>
    </ul>
  </li>
</ul>

<h2 id="9-sources">9. Sources</h2>
<ul>
  <li><a href="http://blog.jamesdbloom.com/JVMInternals.html">JVM Internals</a></li>
  <li><a href="https://www.cubrid.org/blog/understanding-jvm-internals/">Understanding JVM Internals</a></li>
  <li><a href="https://javatutorial.net/jvm-explained">JVM Explained</a></li>
  <li><a href="https://javainterviewpoint.com/java-virtual-machine-architecture-in-java/">Java Virtual Machine Architecture in Java</a></li>
  <li><a href="https://www.geeksforgeeks.org/jvm-works-jvm-architecture/">How JVM Works - JVM Architecture</a></li>
  <li><a href="https://www.guru99.com/java-virtual-machine-jvm.html">Java Virtual Machine (JVM) &amp; its Architecture</a></li>
</ul>]]></content>
      

      
      
      
      
      

      <author>
        <name></name>
        
        
      </author>

      
        
      

      
        <category term="Java" />
      
        <category term="JVM" />
      

      
      
        <summary type="html"><![CDATA[Complete guide to Java Virtual Machine architecture: class loading, memory areas, execution engine, JIT compiler, and garbage collection explained.]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mouaad.aallam.com/assets/images/blog/JVM.png" />
        <media:content medium="image" url="https://mouaad.aallam.com/assets/images/blog/JVM.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
    <entry>
      

      <title type="html">Reactive Programming with RxJava</title>
      <link href="https://mouaad.aallam.com/reactivex-rxjava/" rel="alternate" type="text/html" title="Reactive Programming with RxJava" />
      <published>2019-01-29T23:06:00+00:00</published>
      <updated>2019-01-29T23:06:00+00:00</updated>
      <id>https://mouaad.aallam.com/reactivex:-rxjava</id>
      
      
        <content type="html" xml:base="https://mouaad.aallam.com/reactivex-rxjava/"><![CDATA[<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/reactivex.png" alt="ReactiveX" width="25%" /></p>
  <figcaption class="caption">Reactive Extensions (ReactiveX)</figcaption>
</div>
<p><br /></p>

<blockquote>
  <p><strong>Update Note</strong>: This RxJava series was written for RxJava 2.x (2019). RxJava 3.x introduced breaking changes and improvements. Core concepts remain the same, but some APIs have changed. Refer to the <a href="https://github.com/ReactiveX/RxJava/wiki/What's-different-in-3.0">RxJava 3.x migration guide</a> for differences.</p>
</blockquote>

<p>Interested in Reactive Extensions and RxJava, I enjoyed reading the excellent book: <a href="https://www.amazon.com/Learning-RxJava-Thomas-Nield/dp/1787120422">Learning RxJava</a> by Thomas Nield, and the following are my notes.</p>

<h2 id="why-rxjava">Why RxJava?</h2>
<ul>
  <li>Concurrency, event handling, obsolete data states, and exception recovery.</li>
  <li>Maintainable, reusable, and evolvable.</li>
  <li>Allows applications to be tactical and evolvable while maintaining stability in production.</li>
</ul>

<h2 id="quickstart">Quickstart</h2>
<p>In ReactiveX, the core type is the <code class="language-plaintext highlighter-rouge">Observable</code> which essentially pushes things. A given <code class="language-plaintext highlighter-rouge">Observable&lt;T&gt;</code> pushes things of type <code class="language-plaintext highlighter-rouge">T</code> through a series of operators until it arrives at an <code class="language-plaintext highlighter-rouge">Observer</code> that consumes the items.
The following is an example of an <code class="language-plaintext highlighter-rouge">Observable&lt;String&gt;</code> that pushes three <code class="language-plaintext highlighter-rouge">String</code> objects:</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="kd">val</span> <span class="py">observable</span> <span class="p">=</span> <span class="nc">Observable</span><span class="p">.</span><span class="nf">just</span><span class="p">(</span><span class="s">"Hello"</span><span class="p">,</span> <span class="s">"world"</span><span class="p">,</span> <span class="s">"!"</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Running this <code class="language-plaintext highlighter-rouge">main</code> method isn’t doing anything other than declare a <code class="language-plaintext highlighter-rouge">Observable&lt;String&gt;</code>. To make this <code class="language-plaintext highlighter-rouge">Observable</code> actually emit these three strings, an <code class="language-plaintext highlighter-rouge">Observer</code> need to <em>subscribe</em> to it and receive the items:</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="kd">val</span> <span class="py">observable</span> <span class="p">=</span> <span class="nc">Observable</span><span class="p">.</span><span class="nf">just</span><span class="p">(</span><span class="s">"Hello"</span><span class="p">,</span> <span class="s">"world"</span><span class="p">,</span> <span class="s">"!"</span><span class="p">)</span>
    <span class="n">observable</span><span class="p">.</span><span class="nf">subscribe</span> <span class="p">{</span>
        <span class="nf">print</span><span class="p">(</span><span class="s">"$it "</span><span class="p">)</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>This time, the output is the following:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Hello world! 
</code></pre></div></div>
<p>What happened here is that <code class="language-plaintext highlighter-rouge">Observable&lt;String&gt;</code> pushed each <code class="language-plaintext highlighter-rouge">String</code> object once at a time to the <code class="language-plaintext highlighter-rouge">Observer</code> lambda.</p>

<p>It’s possible to use several operators between <code class="language-plaintext highlighter-rouge">Observable</code> and <code class="language-plaintext highlighter-rouge">Observer</code> to transform each pushed item or manipulate them, the following is an example of <code class="language-plaintext highlighter-rouge">map()</code>:</p>
<div class="language-kotlin highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fun</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
    <span class="kd">val</span> <span class="py">observable</span> <span class="p">=</span> <span class="nc">Observable</span><span class="p">.</span><span class="nf">just</span><span class="p">(</span><span class="s">"Hello"</span><span class="p">,</span> <span class="s">"world"</span><span class="p">,</span> <span class="s">"!"</span><span class="p">)</span>
    <span class="n">observable</span><span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="n">it</span><span class="p">.</span><span class="nf">uppercase</span><span class="p">()</span> <span class="p">}.</span><span class="nf">subscribe</span> <span class="p">{</span> <span class="nf">print</span><span class="p">(</span><span class="s">"$it "</span><span class="p">)</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>The output should be:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>HELLO WORLD!
</code></pre></div></div>

<h2 id="rxjava-vs-java-8-streams">RxJava vs Java 8 streams</h2>
<p>How <code class="language-plaintext highlighter-rouge">Observable</code> is any different from Java 8 <em>Streams</em> or Kotlin <em>sequences</em>? The key difference is that <code class="language-plaintext highlighter-rouge">Observable</code> <em>pushes</em> the items while Streams and sequences <em>pull</em> the items.</p>

<h2 id="rxjava-series-guide">RxJava Series Guide</h2>

<p>This is a comprehensive guide to RxJava organized by topic. Follow the links below for in-depth coverage:</p>

<h3 id="fundamentals">Fundamentals</h3>
<ul>
  <li><a href="https://mouaad.aallam.com/rxjava-observable-and-observer">Observable &amp; Observer</a> - Core concepts and Observable factories</li>
  <li><a href="https://mouaad.aallam.com/rxjava-hot-vs-cold-observable">Hot vs Cold Observable</a> - Understanding observable behavior patterns</li>
  <li><a href="https://mouaad.aallam.com/rxjava-observable-factories">Observable Factories</a> - Additional factory methods (range, interval, timer, etc.)</li>
  <li><a href="https://mouaad.aallam.com/rxjava-disposing">Disposing</a> - Resource management and stopping emissions</li>
</ul>

<h3 id="operators">Operators</h3>
<ul>
  <li><strong>Filtering &amp; Control</strong>: <a href="https://mouaad.aallam.com/rxjava-supressing-operators">Suppressing</a> - filter, take, skip, distinct</li>
  <li><strong>Transformation</strong>: <a href="https://mouaad.aallam.com/rxjava-transforming-operators">Transforming</a> - map, flatMap, concatMap, switchMap</li>
  <li><strong>Aggregation</strong>: <a href="https://mouaad.aallam.com/rxjava-reducing-operators">Reducing</a> - count, reduce, all, any</li>
  <li><strong>Collection</strong>: <a href="https://mouaad.aallam.com/rxjava-collection-operators">Collection</a> - toList, toMap, collect</li>
  <li><strong>Error Handling</strong>: <a href="https://mouaad.aallam.com/rxjava-recovery-operators">Recovery</a> - onErrorReturn, onErrorResumeNext</li>
  <li><strong>Side Effects</strong>: <a href="https://mouaad.aallam.com/rxjava-action-operators">Action</a> - doOnNext, doOnComplete, doOnError</li>
</ul>

<h3 id="advanced-topics">Advanced Topics</h3>
<ul>
  <li><a href="https://mouaad.aallam.com/rxjava-combining-observables">Combining Observables</a> - merge, concat, zip, combineLatest</li>
  <li><a href="https://mouaad.aallam.com/rxjava-multicasting">Multicasting</a> - ConnectableObservable and sharing streams</li>
  <li><a href="https://mouaad.aallam.com/rxjava-replaying-and-caching">Replaying and Caching</a> - replay() and cache() operators</li>
  <li><a href="https://mouaad.aallam.com/rxjava-subjects">Subjects</a> - PublishSubject, BehaviorSubject, and more</li>
  <li><a href="https://mouaad.aallam.com/rxjava-concurrency">Concurrency</a> - subscribeOn and observeOn with Schedulers</li>
  <li><a href="https://mouaad.aallam.com/rxjava-parallelisation">Parallelisation</a> - Parallel execution strategies</li>
</ul>

<h3 id="flow-control">Flow Control</h3>
<ul>
  <li><a href="https://mouaad.aallam.com/rxjava-buffering">Buffering</a> - Batch emissions into collections</li>
  <li><a href="https://mouaad.aallam.com/rxjava-windowing">Windowing</a> - Batch emissions into separate Observables</li>
  <li><a href="https://mouaad.aallam.com/rxjava-throttling">Throttling</a> - Control emission rate</li>
  <li><a href="https://mouaad.aallam.com/rxjava-switching">Switching</a> - Cancel previous Observables</li>
</ul>

<h3 id="backpressure">Backpressure</h3>
<ul>
  <li><a href="https://mouaad.aallam.com/rxjava-backpressure">Backpressure</a> - Understanding and handling backpressure</li>
  <li><a href="https://mouaad.aallam.com/rxjava-flowable">Flowable</a> - Observable with backpressure support</li>
  <li><a href="https://mouaad.aallam.com/rxjava-subscriber">Subscriber</a> - Consuming Flowables</li>
</ul>

<h3 id="customization">Customization</h3>
<ul>
  <li><a href="https://mouaad.aallam.com/rxjava-transformers">Transformers</a> - Reusable operator chains</li>
  <li><a href="https://mouaad.aallam.com/rxjava-custom-operators">Custom Operators</a> - Building your own operators</li>
</ul>

<h2 id="sources">Sources</h2>
<ul>
  <li><a href="https://www.amazon.com/Learning-RxJava-Thomas-Nield/dp/1787120422">Learning RxJava</a></li>
  <li><a href="http://reactivex.io/documentation">ReactiveX Documentation</a></li>
  <li><a href="https://github.com/ReactiveX/RxJava">RxJava Github</a></li>
  <li><a href="https://rxmarbles.com/">RxMarbles</a></li>
</ul>

<p><em>Note: code examples in this article are written in Kotlin to showcase the interoperability between Java and Kotlin, however, for Kotlin projects, it is most likely better to use <a href="https://github.com/ReactiveX/RxKotlin">RxKotlin</a>.</em></p>]]></content>
      

      
      
      
      
      

      <author>
        <name></name>
        
        
      </author>

      
        
      

      
        <category term="ReactiveX" />
      
        <category term="RxJava" />
      
        <category term="Java" />
      
        <category term="Kotlin" />
      

      
      
        <summary type="html"><![CDATA[Introduction to RxJava and reactive programming. Learn the fundamentals of ReactiveX for building asynchronous, event-based applications in Java.]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mouaad.aallam.com/assets/images/blog/reactivex.png" />
        <media:content medium="image" url="https://mouaad.aallam.com/assets/images/blog/reactivex.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
    <entry>
      

      <title type="html">Java 8 Interface Methods for Android</title>
      <link href="https://mouaad.aallam.com/java-8-interface-methods-for-android/" rel="alternate" type="text/html" title="Java 8 Interface Methods for Android" />
      <published>2018-11-23T18:07:00+00:00</published>
      <updated>2018-11-23T18:07:00+00:00</updated>
      <id>https://mouaad.aallam.com/java-8-interface-methods-for-android</id>
      
      
        <content type="html" xml:base="https://mouaad.aallam.com/java-8-interface-methods-for-android/"><![CDATA[<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/android_desugar.png" alt="Java 8 language feature support using desugar bytecode transformations." width="75%" /></p>
  <figcaption class="caption">Java 8 language feature support using desugar bytecode transformations.</figcaption>
</div>
<p><br /></p>

<p>Recently, I enjoyed reading a <a href="https://jakewharton.com/androids-java-8-support">blog post</a> by Jake Wharton about how Android supports Java 8 features using D8.</p>

<p>The blog post goes through the following processes to understand how D8 works:</p>
<ol>
  <li>Write Java code. (.java)</li>
  <li>Compile to ByteCode.(.class)</li>
  <li>Compile to Dalvik Executable. (.dex)</li>
  <li>Analysis of the generated files.</li>
</ol>

<p>In the blog post, the above process allows us to understand what happens under the hood when some Java 8 features (Lambdas and APIs) are desugared using D8.</p>

<p>In this post, we will use the same process to understand how <code class="language-plaintext highlighter-rouge">default</code> methods and <code class="language-plaintext highlighter-rouge">static</code> methods in Java 8 interfaces are desugared using D8. To better understand this post, I heavily recommend reading Jake Wharton’s post first.</p>

<h2 id="compile-java-8-code">Compile Java 8 Code</h2>
<p>We will try to analyse the following code :</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Java8</span> <span class="o">{</span>

  <span class="kd">interface</span> <span class="nc">Logger</span> <span class="o">{</span>
    <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="nc">String</span> <span class="n">s</span><span class="o">);</span>

    <span class="k">default</span> <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="nc">String</span> <span class="n">tag</span><span class="o">,</span> <span class="nc">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">log</span><span class="o">(</span><span class="n">tag</span> <span class="o">+</span> <span class="s">": "</span> <span class="o">+</span> <span class="n">s</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="kd">static</span> <span class="nc">Logger</span> <span class="nf">systemOut</span><span class="o">()</span> <span class="o">{</span>
      <span class="k">return</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">::</span><span class="n">println</span><span class="o">;</span>
    <span class="o">}</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">...</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">sayHi</span><span class="o">(</span><span class="n">s</span> <span class="o">-&gt;</span> <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">s</span><span class="o">));</span>
    <span class="nc">Logger</span><span class="o">.</span><span class="na">systemOut</span><span class="o">().</span><span class="na">log</span><span class="o">(</span><span class="s">"hello from static"</span><span class="o">);</span>
  <span class="o">}</span>

  <span class="kd">private</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">sayHi</span><span class="o">(</span><span class="nc">Logger</span> <span class="n">logger</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="s">"Hello!"</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="s">"hello from"</span><span class="o">,</span> <span class="s">"default"</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>We compile the java code:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ javac *.java
$ ls
Java8.java  Java8.class  Java8$Logger.class
</code></pre></div></div>
<p>Executing the above code gives the following output:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ java Java8
Hello!
hello from: default
hello from static
</code></pre></div></div>
<p>Then we compile the bytecode to dex using D8:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ $ANDROID_HOME/build-tools/28.0.2/d8 --release --lib $ANDROID_HOME/platforms/android-28/android.jar --output . *.class
$ ls
Java8.java  Java8.class  Java8$Logger.class  classes.dex
</code></pre></div></div>
<p>Our focus here is the <code class="language-plaintext highlighter-rouge">default</code> and <code class="language-plaintext highlighter-rouge">static</code> methods in the <code class="language-plaintext highlighter-rouge">Logger</code> interface.</p>

<h2 id="dex-analysis">Dex Analysis</h2>
<p>To see how D8 desugared interface’s <code class="language-plaintext highlighter-rouge">static</code> and <code class="language-plaintext highlighter-rouge">default</code> methods, we will use <code class="language-plaintext highlighter-rouge">dexdump</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ $ANDROID_HOME/build-tools/28.0.2/dexdump -d classes.dex
</code></pre></div></div>
<p>We get a lot of output (the full output can be found <a href="https://gist.github.com/Aallam/0e6de2591ece329fb6ade9fb98bef444">here</a>).</p>

<h2 id="default-methods">Default Methods</h2>
<p>Firs, we find the following output:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Class #0            -
  Class descriptor  : 'LJava8$Logger-CC;'
  Access flags      : 0x1011 (PUBLIC FINAL SYNTHETIC)
  Superclass        : 'Ljava/lang/Object;'
  Interfaces        -
  Static fields     -
  Instance fields   -
</code></pre></div></div>
<p>A new class <code class="language-plaintext highlighter-rouge">Java8$Logger-CC</code> has been generated! (We know it’s generated because of the <code class="language-plaintext highlighter-rouge">SYNTHETIC</code> flag). This class has <code class="language-plaintext highlighter-rouge">Object</code> as superclass and doesn’t implement any interfaces and have no static or instance fields.</p>

<p>Now let’s check these class methods. The class has two methods, the first one is <code class="language-plaintext highlighter-rouge">$default$log</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Direct methods    -
    #0              : (in LJava8$Logger-CC;)
      name          : '$default$log'
      type          : '(LJava8$Logger;Ljava/lang/String;Ljava/lang/String;)V'
      access        : 0x0009 (PUBLIC STATIC)
</code></pre></div></div>
<p>We can read that this method is a <code class="language-plaintext highlighter-rouge">static</code> method and takes as arguments a <code class="language-plaintext highlighter-rouge">Logger</code> plus the same arguments as our default method in our <code class="language-plaintext highlighter-rouge">Logger</code> interface! 
The content of the method is:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[000434] Java8.Logger-CC.$default$log:(LJava8$Logger;Ljava/lang/String;Ljava/lang/String;)V
|0000: new-instance v0, Ljava/lang/StringBuilder; // type@000c
|0002: invoke-direct {v0}, Ljava/lang/StringBuilder;.&lt;init&gt;:()V // method@0012
|0005: invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; // method@0013
|0008: const-string v2, ": " // string@0001
|000a: invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; // method@0013
|000d: invoke-virtual {v0, v3}, Ljava/lang/StringBuilder;.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; // method@0013
|0010: invoke-virtual {v0}, Ljava/lang/StringBuilder;.toString:()Ljava/lang/String; // method@0014
|0013: move-result-object v2
|0014: invoke-interface {v1, v2}, LJava8$Logger;.log:(Ljava/lang/String;)V // method@0009
|0017: return-void
</code></pre></div></div>
<p>Even though the output looks complicated, the code here is actually simple and its logic is equivalent to the implementation of the <code class="language-plaintext highlighter-rouge">default</code> method in <code class="language-plaintext highlighter-rouge">Logger</code> interface!
The equivalent Java code of the method can be the following :</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">defaultLog</span><span class="o">(</span><span class="nc">Logger</span> <span class="n">logger</span><span class="o">,</span> <span class="nc">String</span> <span class="n">tag</span><span class="o">,</span> <span class="nc">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">tag</span> <span class="o">+</span> <span class="s">":"</span> <span class="o">+</span> <span class="n">s</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>
<p>We can conclude that the <code class="language-plaintext highlighter-rouge">default</code> method in interfaces are desugared to <code class="language-plaintext highlighter-rouge">static</code> methods in a newly generated utility class (<code class="language-plaintext highlighter-rouge">Loger-CC</code>).</p>

<h2 id="static-method">Static Method</h2>
<p>Based on what we already saw before, we can have a guess how <code class="language-plaintext highlighter-rouge">static</code> methods in interfaces are desugared! Let’s check!
The generated class <code class="language-plaintext highlighter-rouge">Loger-CC</code> have a second <code class="language-plaintext highlighter-rouge">static</code> method! And without surprise, its name is <code class="language-plaintext highlighter-rouge">systemOut</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#1            : (in LJava8$Logger-CC;)
  name        : 'systemOut'
  type        : '()LJava8$Logger;'
  access      : 0x0009 (PUBLIC STATIC)
</code></pre></div></div>
<p>The method <code class="language-plaintext highlighter-rouge">systemOut</code> in <code class="language-plaintext highlighter-rouge">Logger-CC</code> take no arguments and returns a <code class="language-plaintext highlighter-rouge">Logger</code> !
The body of the method is:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>|[00040c] Java8.Logger-CC.systemOut:()LJava8$Logger;
|0000: sget-object v0, Ljava/lang/System;.out:Ljava/io/PrintStream; // field@0002
|0002: invoke-virtual {v0}, Ljava/lang/Object;.getClass:()Ljava/lang/Class; // method@0011
|0005: new-instance v1, L-$$Lambda$teOjDu261Kz9uXGt1wlPvIP5S04; // type@0001
|0007: invoke-direct {v1, v0}, L-$$Lambda$teOjDu261Kz9uXGt1wlPvIP5S04;.&lt;init&gt;:(Ljava/io/PrintStream;)V // method@0004
|000a: return-object v1
</code></pre></div></div>
<p>Without surprise, the code is equivalent to our implementation of the <code class="language-plaintext highlighter-rouge">static</code> method in <code class="language-plaintext highlighter-rouge">systemOut</code> in the interface <code class="language-plaintext highlighter-rouge">Logger</code> (<code class="language-plaintext highlighter-rouge">$Lambda$teOjDu261Kz9uXGt1wlPvIP5S04</code> is a class that corresponds to the lambda <code class="language-plaintext highlighter-rouge">System.out::println</code> in our implementation).</p>

<p>The equivalent java code can be:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">static</span> <span class="nc">Logger</span> <span class="nf">systemOut</span><span class="o">()</span> <span class="o">{</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">Lambda</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">);</span> <span class="c1">//System.out::println</span>
<span class="o">}</span>
</code></pre></div></div>

<h2 id="conclusion">Conclusion</h2>

<p>The following Java code is an equivalent of our <code class="language-plaintext highlighter-rouge">Java8</code> class above (PS: I changed some methods/classes names for clarity) :</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">java.io.PrintStream</span><span class="o">;</span>

<span class="kd">class</span> <span class="nc">Java8Desugared</span> <span class="o">{</span>

  <span class="kd">interface</span> <span class="nc">Logger</span> <span class="o">{</span>
    <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="nc">String</span> <span class="n">s</span><span class="o">);</span>
    <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="nc">String</span> <span class="n">tag</span><span class="o">,</span> <span class="nc">String</span> <span class="n">s</span><span class="o">);</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kd">class</span> <span class="nc">LoggerCC</span> <span class="o">{</span>

    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">defaultLog</span><span class="o">(</span><span class="nc">Logger</span> <span class="n">logger</span><span class="o">,</span> <span class="nc">String</span> <span class="n">tag</span><span class="o">,</span> <span class="nc">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="n">tag</span> <span class="o">+</span> <span class="s">":"</span> <span class="o">+</span> <span class="n">s</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kd">static</span> <span class="nc">Logger</span> <span class="nf">systemOut</span><span class="o">()</span> <span class="o">{</span>
      <span class="k">return</span> <span class="k">new</span> <span class="nf">LambdaSystemOut</span><span class="o">(</span><span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">);</span>
    <span class="o">}</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kd">class</span> <span class="nc">LambdaSystemOut</span> <span class="kd">implements</span> <span class="nc">Logger</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="nc">PrintStream</span> <span class="n">ps</span><span class="o">;</span>

    <span class="kd">public</span> <span class="nf">LambdaSystemOut</span><span class="o">(</span><span class="nc">PrintStream</span> <span class="n">ps</span><span class="o">)</span> <span class="o">{</span>
      <span class="k">this</span><span class="o">.</span><span class="na">ps</span> <span class="o">=</span> <span class="n">ps</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nd">@Override</span> <span class="kd">public</span> <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="nc">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">ps</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">s</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="nd">@Override</span> <span class="kd">public</span> <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="nc">String</span> <span class="n">tag</span><span class="o">,</span> <span class="nc">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
      <span class="nc">LoggerCC</span><span class="o">.</span><span class="na">defaultLog</span><span class="o">(</span><span class="k">this</span><span class="o">,</span> <span class="n">tag</span><span class="o">,</span> <span class="n">s</span><span class="o">);</span>
    <span class="o">}</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">...</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">sayHi</span><span class="o">(</span><span class="nc">LambdaSayHi</span><span class="o">.</span><span class="na">INSTANCE</span><span class="o">);</span>
    <span class="nc">LoggerCC</span><span class="o">.</span><span class="na">systemOut</span><span class="o">().</span><span class="na">log</span><span class="o">(</span><span class="s">"hello from static"</span><span class="o">);</span>
  <span class="o">}</span>

  <span class="kd">private</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">sayHi</span><span class="o">(</span><span class="nc">Logger</span> <span class="n">logger</span><span class="o">)</span> <span class="o">{</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="s">"Hello!"</span><span class="o">);</span>
    <span class="n">logger</span><span class="o">.</span><span class="na">log</span><span class="o">(</span><span class="s">"hello from"</span><span class="o">,</span> <span class="s">"default"</span><span class="o">);</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kd">class</span> <span class="nc">LambdaSayHi</span> <span class="kd">implements</span> <span class="nc">Logger</span> <span class="o">{</span>
    <span class="kd">static</span> <span class="kd">final</span> <span class="nc">LambdaSayHi</span> <span class="no">INSTANCE</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">LambdaSayHi</span><span class="o">();</span>

    <span class="kd">private</span> <span class="nf">LambdaSayHi</span><span class="o">()</span> <span class="o">{}</span>

    <span class="nd">@Override</span> <span class="kd">public</span> <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="nc">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
      <span class="n">lambdaContent</span><span class="o">(</span><span class="n">s</span><span class="o">);</span>
    <span class="o">}</span>

    <span class="nd">@Override</span> <span class="kd">public</span> <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="nc">String</span> <span class="n">tag</span><span class="o">,</span> <span class="nc">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
      <span class="nc">LoggerCC</span><span class="o">.</span><span class="na">defaultLog</span><span class="o">(</span><span class="k">this</span><span class="o">,</span> <span class="n">tag</span><span class="o">,</span> <span class="n">s</span><span class="o">);</span>
    <span class="o">}</span>
  <span class="o">}</span>

  <span class="kd">static</span> <span class="kt">void</span> <span class="nf">lambdaContent</span><span class="o">(</span><span class="nc">String</span> <span class="n">s</span><span class="o">)</span> <span class="o">{</span>
    <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">s</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Compiling and running the above code gives the same output as our <code class="language-plaintext highlighter-rouge">Java8</code> class:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ javac Java8Desugared.java
$ java Java8Desugared
Hello!
hello from:default
hello from static
</code></pre></div></div>

<h2 id="sources">Sources</h2>
<ul>
  <li><a href="https://jakewharton.com/androids-java-8-support">Android’s Java 8 Support</a></li>
  <li><a href="https://source.android.com/devices/tech/dalvik/dalvik-bytecode">Dalvik bytecode</a></li>
</ul>]]></content>
      

      
      
      
      
      

      <author>
        <name></name>
        
        
      </author>

      
        
      

      
        <category term="Java" />
      
        <category term="Android" />
      

      
      
        <summary type="html"><![CDATA[Explore Java 8 interface features for Android development: default methods, static methods, and functional interfaces with practical examples.]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mouaad.aallam.com/assets/images/blog/android_desugar.png" />
        <media:content medium="image" url="https://mouaad.aallam.com/assets/images/blog/android_desugar.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
    <entry>
      

      <title type="html">Hello World!</title>
      <link href="https://mouaad.aallam.com/hello-world/" rel="alternate" type="text/html" title="Hello World!" />
      <published>2016-04-06T00:00:00+00:00</published>
      <updated>2016-04-06T00:00:00+00:00</updated>
      <id>https://mouaad.aallam.com/hello-world</id>
      
      
        <content type="html" xml:base="https://mouaad.aallam.com/hello-world/"><![CDATA[<p>Hello and Welcome !</p>

<figure class="highlight"><pre><code class="language-c" data-lang="c"><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"hello, world</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
        <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>

<p>For a long time, I had the idea of setting up my own website/blog, I’ve done some shy attempts before but this one is the one! So welcome to my blog, and to this unavoidable “Hello, world!” post! :D</p>

<p>I’ve built this blog with <a href="http://jekyllbootstrap.com/">Jekyll</a> using the <a href="https://github.com/sergiokopplin/indigo">Indigo theme</a>, the code source is available at <a href="https://github.com/Aallam/aallam.github.io">Github</a>.</p>

<p>Cheers,<br />
Mouaad</p>]]></content>
      

      
      
      
      
      

      <author>
        <name></name>
        
        
      </author>

      
        <category term="[&quot;General&quot;]" />
      

      
        <category term="jekyll" />
      
        <category term="git" />
      

      
      
        <summary type="html"><![CDATA[The first post of the website/blog]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mouaad.aallam.com/assets/images/generated/posts/2016-04-06-hello-world.png" />
        <media:content medium="image" url="https://mouaad.aallam.com/assets/images/generated/posts/2016-04-06-hello-world.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
</feed>
