<?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-08-03T10:13:36+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">Configuration Is a Distributed System</title>
      <link href="https://mouaad.aallam.com/configuration-is-a-distributed-system/" rel="alternate" type="text/html" title="Configuration Is a Distributed System" />
      <published>2026-08-02T12:00:00+00:00</published>
      <updated>2026-08-02T12:00:00+00:00</updated>
      <id>https://mouaad.aallam.com/configuration-is-a-distributed-system</id>
      
      
        <content type="html" xml:base="https://mouaad.aallam.com/configuration-is-a-distributed-system/"><![CDATA[<p>A configuration value exists in the secret manager. The synchronization controller reports success. The Kubernetes Secret contains the expected key. The web pods are healthy. A background worker still fails at startup because the value is missing.</p>

<p>The usual question is: <em>where is the configuration wrong?</em></p>

<p>That question assumes configuration is one thing in one place. In production it is usually a piece of state copied through several systems, transformed along the way, and activated by more than one process. The value in the source of truth is only the first copy.</p>

<p>A more useful question is: <em>how far did this revision get?</em></p>

<p>Configuration is a distributed system. It has authorities, replicas, propagation delays, schemas, consumers, version skew, partial failures, and rarely a transaction covering the whole path. Treating it as a map of keys and values hides the part that causes most operational failures: delivery.</p>

<h2 id="the-source-of-truth-is-only-the-source">The source of truth is only the source</h2>

<p>Consider a common path for an application credential:</p>

<pre class="mermaid">
flowchart TB
    Authority["External authority"] --&gt;|fetch| Sync["Synchronization controller"]
    Sync --&gt;|materialize| Secret["Kubernetes Secret"]
    Template["Pod template"] -.-&gt;|references| Secret
    Secret --&gt;|resolve when container starts| Env["Container environment"]
    Secret --&gt;|project through kubelet| File["Mounted file"]
    Env --&gt;|read at startup| Process["Workload process"]
    File --&gt;|reread or reload| Process
    Process --&gt;|validate and activate| Subsystem["Configured subsystem"]

    classDef authority fill:#fff3d6,stroke:#d1a11f,color:#4f3200
    classDef control fill:#efe7ff,stroke:#6a3fd4,color:#20113a
    classDef state fill:#e8f1ff,stroke:#2f5da8,color:#102a43
    classDef runtime fill:#d8f3ef,stroke:#1b8c7a,color:#0f3c36
    class Authority authority
    class Sync,Template control
    class Secret state
    class Env,File,Process,Subsystem runtime
</pre>

<p><strong>Two delivery paths.</strong> The pod template references the Secret but does not contain its value. Environment delivery happens when a container starts; file delivery follows kubelet projection and still requires the process to reread or reload it.</p>

<p>Each edge is a contract.</p>

<p>The controller needs the correct source path, permissions, refresh policy, target name, key mapping, and transformation. The workload manifest needs to reference the correct Secret and key. A running process cannot receive a changed environment variable; a controlled Pod rollout is the normal way to create processes with the new environment. The process must parse the value and make it available to the subsystem that uses it. Every relevant workload needs a complete path of its own.</p>

<p>None of those steps is implied by the previous one. A value can exist in the secret manager without being selected by the synchronization resource. A Kubernetes Secret can be current while existing Pods retain old environment variables. A mounted file can change while an application that read it once at startup continues using the previous value. A web Deployment can be wired correctly while a worker Deployment is forgotten.</p>

<p>Calling the secret manager the source of truth is still useful: it identifies the authority allowed to declare the desired value. It does not prove the state of any running consumer.</p>

<h2 id="four-states-and-an-evidence-plane">Four states and an evidence plane</h2>

<p>It helps to give each stage a name. A production configuration change moves through four lifecycle states, while an evidence plane makes every transition verifiable.</p>

<p><strong>Declared.</strong> An owner has recorded a desired revision in the authoritative system. This might be a Git commit, a secret-manager version, a configuration-service record, or an API mutation.</p>

<p><strong>Materialized.</strong> The desired revision has been rendered into the system-specific object from which a workload can receive it: a Kubernetes Secret or ConfigMap, a generated file, a service response, or a release artifact.</p>

<p><strong>Delivered.</strong> The workload has access to that revision. For a container this may mean a new environment, a projected file, or a successful runtime fetch.</p>

<p><strong>Activated.</strong> The running process has parsed, validated, and begun using the revision. Delivery and activation are different when applications cache configuration, reload asynchronously, reject invalid updates, or contain several independently configured subsystems.</p>

<p><strong>Evidence plane.</strong> For every intended consumer, an operator can determine which revision reached each lifecycle state without exposing its value. Evidence is not another copy of configuration; it is attached to every transition.</p>

<p>A successful declaration is therefore only the start of a change, not evidence that it reached runtime.</p>

<p>This vocabulary also narrows incidents quickly. “The Secret is correct” establishes materialization. It says nothing about delivery or activation. “The rollout finished” establishes that Pods were replaced. It does not prove the process accepted the intended revision. A healthy endpoint may prove the process can serve traffic, but unless health includes the relevant configuration invariant, it may not prove activation either.</p>

<h2 id="presence-is-not-propagation">Presence is not propagation</h2>

<p>Kubernetes makes the distinction concrete. A ConfigMap projected as a normal volume is eventually updated by the kubelet, subject to its synchronization and cache propagation delays. The application uses the new value only if it rereads or reloads the file; one that reads only at startup continues using its previous in-memory state. A <code class="language-plaintext highlighter-rouge">subPath</code> mount is an important exception because it does not receive ConfigMap updates. A running process never observes later ConfigMap changes through its environment; an intentional Pod replacement is the documented mechanism for rolling out the new value. Without one, ordinary scaling can leave a service running a mixture of old and new values. Container recreation can introduce an even narrower form of skew because the kubelet resolves referenced values when it creates each container.</p>

<p>Secret synchronization adds another independent clock. The External Secrets Operator, for example, supports <code class="language-plaintext highlighter-rouge">CreatedOnce</code>, <code class="language-plaintext highlighter-rouge">Periodic</code>, and <code class="language-plaintext highlighter-rouge">OnChange</code> refresh policies. <code class="language-plaintext highlighter-rouge">Periodic</code> rereads the external provider on an interval. <code class="language-plaintext highlighter-rouge">OnChange</code> reacts to changes in the <code class="language-plaintext highlighter-rouge">ExternalSecret</code> resource rather than provider-side rotation. <code class="language-plaintext highlighter-rouge">CreatedOnce</code> normally creates the target once, but reconciles it again if the target Secret is deleted or altered; recreating the <code class="language-plaintext highlighter-rouge">ExternalSecret</code> also begins a new lifecycle. “The controller is installed” therefore tells us very little about when a particular change should materialize.</p>

<p>The wider lesson is not specific to Kubernetes: every edge in the graph has a propagation policy. It might be push-based, polled, rollout-bound, startup-only, manually triggered, or immutable. If that policy is left implicit, operators will invent one in their heads, and their models will disagree during an incident.</p>

<p>A useful configuration specification answers four questions for every edge:</p>

<ul>
  <li>What event starts propagation?</li>
  <li>What is the expected delay?</li>
  <li>How is failure surfaced and retried?</li>
  <li>What evidence proves the next stage accepted the revision?</li>
</ul>

<p>Without those answers, eventual consistency becomes “probably updated by now.”</p>

<h2 id="the-consumer-set-is-larger-than-it-looks">The consumer set is larger than it looks</h2>

<p>Teams usually wire configuration into the workload that uses the feature. That sounds precise and least-privileged. It can still be incomplete.</p>

<p>Suppose the web process uses <code class="language-plaintext highlighter-rouge">EVENT_SIGNING_KEY</code>, while a worker never signs an event. If both processes boot through one configuration schema that marks the key as globally required, the worker is also a consumer of that configuration for startup purposes. It can fail before reaching any feature-specific code.</p>

<p>This creates an architectural choice.</p>

<p>One option is to deliver the value to every workload that runs the global validator. That restores the runtime invariant, but it widens secret distribution. Another is to split configuration schemas by process role so that each workload validates only what it can use. That preserves least privilege, but introduces more schemas and makes shared startup paths less uniform. A third is conditional validation: keep a shared schema, but require a field only when the relevant capability is enabled, then assert the invariant again at the feature boundary. This limits distribution while keeping common parsing, at the cost of a more stateful contract.</p>

<p>None of these choices is universally correct. The mistake is using one definition of <em>consumer</em> in application code and another in deployment configuration.</p>

<p>For delivery purposes, the consumer set includes every workload that either uses the value or requires it to start. That includes web processes, workers, scheduled jobs, migration hooks, administrative commands, and sometimes sidecars. Short-lived jobs are easy to miss because they may not exist when the change is inspected, yet the next deployment can create them with stale wiring.</p>

<blockquote class="markdown-alert markdown-alert-important">
  <p><span class="markdown-alert-title"><svg data-component="Octicon" class="octicon octicon-report markdown-alert-icon" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v9.5A1.75 1.75 0 0 1 14.25 13H8.06l-2.573 2.573A1.458 1.458 0 0 1 3 14.543V13H1.75A1.75 1.75 0 0 1 0 11.25Zm1.75-.25a.25.25 0 0 0-.25.25v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25Zm7 2.25v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 9a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg>Important</span>
For every workload that consumes or startup-validates a configuration field, there must be a complete delivery path from its declared source to activation in that workload.</p>
</blockquote>

<p>This is a graph property, not a check that a key appears somewhere in a repository.</p>

<h2 id="version-skew-is-normal">Version skew is normal</h2>

<p>A rolling deployment intentionally runs old and new Pods at the same time. Kubernetes controls the overlap through <code class="language-plaintext highlighter-rouge">maxUnavailable</code> and <code class="language-plaintext highlighter-rouge">maxSurge</code>; it does not provide an instant fleet-wide transition. Configuration changes therefore need a compatibility story just as binary changes do.</p>

<p>The dangerous case is a coupled change:</p>

<ul>
  <li>the old binary accepts configuration schema <code class="language-plaintext highlighter-rouge">v1</code>;</li>
  <li>the new binary requires schema <code class="language-plaintext highlighter-rouge">v2</code>;</li>
  <li>the configuration is stored and rolled out independently.</li>
</ul>

<p>Publishing <code class="language-plaintext highlighter-rouge">v2</code> first can break old instances. Deploying the binary first can break new instances that still receive <code class="language-plaintext highlighter-rouge">v1</code>. A rolling update creates an overlap in which incompatible binary/configuration combinations are possible unless the release process or delivery mechanism prevents them.</p>

<p>The usual solution is an expand-and-contract sequence:</p>

<ol>
  <li>Deploy code that accepts both the old and new configuration shapes.</li>
  <li>Verify that the compatible binary is active everywhere that matters.</li>
  <li>Publish the new configuration revision gradually.</li>
  <li>Verify activation across the fleet.</li>
  <li>Remove support for the old shape in a later release.</li>
</ol>

<p>Credential rotation is the same problem with an external participant. If a producer begins signing with a new key before consumers can verify it, or a database password changes before connection pools receive it, rollback may not be as simple as restoring a file. Safe rotation often needs an overlap period in which both revisions are accepted, followed by evidence that the old revision is no longer in use.</p>

<p>This is why configuration deserves versioning. A version is not only history in Git. It is an identity that can travel through the graph and let us compare desired, materialized, delivered, and activated state.</p>

<h2 id="validate-at-the-boundary-that-owns-the-failure">Validate at the boundary that owns the failure</h2>

<p>“Fail fast” is good advice until every layer fails for the same reason and nobody can tell which boundary was broken.</p>

<p>Validation should be layered.</p>

<p><strong>Before deployment</strong>, validate syntax, schema, generated manifests, references, and the expected consumer set. These checks catch structural errors without needing production credentials.</p>

<p><strong>During reconciliation</strong>, report whether the desired source was fetched and the target object was produced. A controller condition should distinguish missing permissions, missing source data, transformation errors, and an intentionally non-refreshing policy.</p>

<p><strong>At process startup</strong>, validate required presence, parsing, ranges, mutually dependent fields, and invariants the application can determine locally. A process should not advertise readiness if it cannot serve correctly with its activated configuration. Readiness should answer whether this replica can serve safely now, not whether the fleet has converged on the desired revision.</p>

<p><strong>During runtime reload</strong>, build and validate a complete candidate before swapping it into use. Updating fields one at a time exposes combinations that never existed in any declared revision. If a candidate is invalid, continuing with the last-known-good revision is often safer than partially activating it.</p>

<p>That last rule has limits. Continuing with an expired or revoked credential may be unsafe, and retaining configuration indefinitely can hide a broken control plane. Last-known-good behavior therefore needs an expiry policy and an explicit degraded state, not silent immortality.</p>

<p>Validation also needs semantic checks. A value can be present, correctly typed, and operationally disastrous. A timeout of <code class="language-plaintext highlighter-rouge">0</code> may parse as an integer but disable a safety boundary. A percentage of <code class="language-plaintext highlighter-rouge">100</code> may be valid syntax but turn a gradual rollout into a global change. The component that understands the meaning should own those invariants.</p>

<h2 id="observe-revisions-not-values">Observe revisions, not values</h2>

<p>During an incident, an operator should be able to answer:</p>

<ul>
  <li>What revision is desired?</li>
  <li>What revision did the synchronization layer materialize?</li>
  <li>What revision did each workload activate?</li>
  <li>When did each transition happen?</li>
  <li>Which consumers are missing, stale, or rejecting the revision?</li>
</ul>

<p>Secrets and other sensitive configuration values should not appear in logs or metrics. Bounded, explicitly non-sensitive effective settings can be useful for diagnosis, but should be selected deliberately rather than dumped wholesale. Hashing is not automatically safe either: hashes of low-entropy configuration can be guessed, and a unique revision label attached to every metric series creates unbounded cardinality.</p>

<p>A better design carries an opaque revision identifier alongside the value. Prefer an identifier assigned by the authority; if a process must derive one, use a keyed digest rather than a bare hash of the configuration. Controllers can record it in status or metadata. Processes can emit it once in a structured startup or reload event and expose it through an authenticated, authorized, and bounded diagnostic inventory. Fleet-level monitoring can then report counts such as “27 of 30 consumers activated the desired revision” and the age of the oldest stale consumer without turning every revision into a permanent time series.</p>

<p>Health and configuration state should also remain distinct. A service may be healthy on its last-known-good revision while configuration convergence is degraded. Collapsing both into one boolean either removes a healthy instance unnecessarily or hides propagation failure. Report service readiness, configuration activation, and convergence separately, then decide which conditions should block rollout.</p>

<h2 id="roll-out-configuration-like-code">Roll out configuration like code</h2>

<p>Configuration can change behavior without changing a binary, which sometimes makes it more dangerous than code. It often receives less testing precisely because it looks smaller.</p>

<p>Google’s SRE guidance for safe configuration changes identifies three useful properties: gradual deployment, rollback, and automatic rollback—or at minimum stopping rollout progress—before a failure removes operator control. Those requirements follow naturally from the distributed-system model.</p>

<p>Gradual rollout limits the number of consumers on a bad revision. A pause between stages creates time to inspect both application outcomes and convergence. Rollback requires preserving the previous revision and knowing whether reversing configuration is sufficient; external state changes may require a forward repair instead. Automatic stopping requires signals tied to the effect of the configuration, not only confirmation that distribution succeeded.</p>

<p>The release unit matters too. If a configuration revision is meaningful only with one binary version, deploy them as one tested artifact or encode their compatibility explicitly. If configuration must remain independently changeable, design overlapping compatibility windows. Independence in the delivery machinery does not create independence in semantics.</p>

<h2 id="test-the-graph">Test the graph</h2>

<p>Most configuration tests focus on the endpoints. A schema test proves the application can parse an example. A deployment test proves a Secret exists. The failure-prone part is the path between them.</p>

<p>Useful tests cover the edges:</p>

<ul>
  <li>the declared source key maps to the intended materialized key;</li>
  <li>every workload in the consumer inventory references the right object;</li>
  <li>generated manifests preserve the reference in every environment;</li>
  <li>startup validation accepts the deployed shape;</li>
  <li>old and new binary/configuration combinations behave as planned;</li>
  <li>rotation, reload, rollback, and last-known-good paths work;</li>
  <li>short-lived jobs and hooks receive the same contract as long-running services;</li>
  <li>observability reports the activated revision without exposing data.</li>
</ul>

<p>Not all of these tests need a cluster. Rendering manifests and comparing them with a declared consumer inventory catches many omissions deterministically. Contract tests can use non-secret placeholders to exercise mappings and parsers. A small integration environment can then verify reconciliation, Pod replacement, reload behavior, and convergence.</p>

<p>The goal is not to reproduce production in CI. It is to prove that every edge has an owner and at least one test at the cheapest layer capable of finding its failures.</p>

<h2 id="configuration-is-deployed-state">Configuration is deployed state</h2>

<p>Configuration is often described as code, which usefully brings review and version control to it. But code in a repository is not running software, and configuration in its authority is not activated state.</p>

<p>Configuration is a propagation graph, and its lifecycle spine is:</p>

<pre class="mermaid">
flowchart LR
    Declared["Declared"] --&gt; Materialized["Materialized"]
    Materialized --&gt; Delivered["Delivered"]
    Delivered --&gt; Activated["Activated"]
    Declared -.-&gt; Evidence["Evidence plane"]
    Materialized -.-&gt; Evidence
    Delivered -.-&gt; Evidence
    Activated -.-&gt; Evidence

    classDef lifecycle fill:#efe7ff,stroke:#6a3fd4,color:#20113a
    classDef evidence fill:#d8f3ef,stroke:#1b8c7a,color:#0f3c36
    class Declared,Materialized,Delivered,Activated lifecycle
    class Evidence evidence
</pre>

<p><strong>The configuration lifecycle.</strong> Solid arrows move a revision toward runtime activation; dotted arrows record the evidence needed to prove where it reached. Real systems fan out into many materializations and consumers around this spine.</p>

<p>Every arrow can delay, retry, transform, reject, or silently retain an older revision. Every fan-out can reach some consumers and miss others. Most rolling or staged rollouts create a period of version skew. Every rollback depends on whether the old world still exists outside the configuration system.</p>

<p>Once those properties are explicit, configuration incidents become less mysterious. Instead of asking whether the value exists, ask which revision each stage holds. Instead of checking one workload, enumerate the consumers. Instead of assuming a rollout makes change atomic, design compatibility for the overlap. Instead of logging secrets, propagate revision identity.</p>

<p>A configuration change is finished when all intended consumers have activated the intended revision and the system can prove it. Everything before that is propagation in progress.</p>

<h2 id="references">References</h2>

<ul>
  <li><a href="https://kubernetes.io/docs/tutorials/configuration/updating-configuration-via-a-configmap/">Updating Configuration via a ConfigMap — Kubernetes</a></li>
  <li><a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">Deployments — Kubernetes</a></li>
  <li><a href="https://external-secrets.io/latest/api/externalsecret/">ExternalSecret API — External Secrets Operator</a></li>
  <li><a href="https://sre.google/workbook/configuration-design/">Configuration Design and Best Practices — Google SRE Workbook</a></li>
</ul>]]></content>
      

      
      
      
      
      

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

      
        
      

      
        <category term="Configuration" />
      
        <category term="Distributed Systems" />
      
        <category term="Kubernetes" />
      
        <category term="Reliability" />
      

      
      
        <summary type="html"><![CDATA[Why production configuration is a propagation graph, how changes move from declaration to activation, and how to design delivery, rollout, validation, and observability around that fact.]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mouaad.aallam.com/assets/images/generated/posts/2026-08-02-configuration-is-a-distributed-system.png" />
        <media:content medium="image" url="https://mouaad.aallam.com/assets/images/generated/posts/2026-08-02-configuration-is-a-distributed-system.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
    <entry>
      

      <title type="html">V8 Memory and the Node Event Loop</title>
      <link href="https://mouaad.aallam.com/v8-memory-and-the-node-event-loop/" rel="alternate" type="text/html" title="V8 Memory and the Node Event Loop" />
      <published>2026-07-28T00:10:00+00:00</published>
      <updated>2026-07-28T00:10:00+00:00</updated>
      <id>https://mouaad.aallam.com/v8-memory-and-the-node-event-loop</id>
      
      
        <content type="html" xml:base="https://mouaad.aallam.com/v8-memory-and-the-node-event-loop/"><![CDATA[<p>Reference notes for myself on two things that turn out to be one thing: how V8 lays out memory and collects garbage, and how Node decides what runs next. They meet at a single point, which is that a garbage-collection pause and a blocked event loop are the same stall seen from two angles.</p>

<p>Two interactive animations do most of the explaining. Each has a guided tour you can step through beat by beat, plus a free mode where you fire operations and watch them move.</p>

<p>Keyboard in both: <code class="language-plaintext highlighter-rouge">↓</code>/<code class="language-plaintext highlighter-rouge">↑</code> step one beat, <code class="language-plaintext highlighter-rouge">←</code>/<code class="language-plaintext highlighter-rouge">→</code> jump sections, <code class="language-plaintext highlighter-rouge">Space</code> play or pause, <code class="language-plaintext highlighter-rouge">R</code> replay, <code class="language-plaintext highlighter-rouge">Home</code>/<code class="language-plaintext highlighter-rouge">End</code> first or last section.</p>

<h2 id="the-v8-heap">The V8 heap</h2>

<div class="interactive-explainer">
  <iframe src="https://mouaad.aallam.com/assets/files/v8-memory-and-the-node-event-loop/v8-memory.html" title="Interactive explainer: how V8 manages memory" loading="lazy" allowfullscreen=""></iframe>
  <div class="interactive-explainer-mobile">
    <span class="interactive-explainer-mobile__eyebrow">Interactive diagram</span>
    <strong>Explore how V8 manages memory</strong>
    <span>Open the guided animation in a full-screen, mobile-friendly view.</span>
    <a href="https://mouaad.aallam.com/assets/files/v8-memory-and-the-node-event-loop/v8-memory.html">Open interactive diagram <span aria-hidden="true">→</span></a>
  </div>
</div>

<p>The model in one paragraph. Most objects live in a heap split into spaces. A small <strong>New space</strong>, itself split into two equal halves, takes most fresh allocations via a bump pointer; anything above the large-object threshold, or covered by pretenuring, skips it. A large <strong>Old space</strong> holds whatever survived long enough to be promoted. Around them sit <strong>Large-object</strong> space for things too big to copy, <strong>Code</strong> space for JIT output, and an immortal <strong>Read-only</strong> space.</p>

<p>The parts that are easiest to get wrong:</p>

<p><strong>Not everything is on the heap.</strong> Small integers are encoded directly in the value and never allocated at all. <code class="language-plaintext highlighter-rouge">ArrayBuffer</code> backing stores, including <code class="language-plaintext highlighter-rouge">Buffer</code> bytes, live outside V8’s managed heap, which is why <code class="language-plaintext highlighter-rouge">--max-old-space-size</code> does not bound them. <code class="language-plaintext highlighter-rouge">process.memoryUsage().arrayBuffers</code> reports them specifically, counted within the broader <code class="language-plaintext highlighter-rouge">external</code> figure. This is the single most common surprise when diagnosing real memory growth.</p>

<p><strong>Minor GC is cheap because of what it does not do.</strong> The Scavenger copies live objects from one semi-space to the other, then flips their roles. Dead objects are never individually traced or copied; their half is reclaimed wholesale. Cost tracks the survivors, not the allocation volume. It is still a stop-the-world pause, just a short parallel one.</p>

<p><strong>Promotion is positional, not a counter.</strong> The rule of thumb is that surviving a second scavenge promotes you to Old space. The mechanism is not a per-object counter, it is an age mark in the semi-space: a reachable survivor sitting below that mark is eligible for promotion. Copy or space pressure can promote survivors earlier, and allocation-site <strong>pretenuring</strong> is a different thing entirely, since it allocates straight into Old space and skips New space altogether. Treat “survives twice” as the common path, not a guarantee.</p>

<p><strong>Marking is transitive, which is the whole point.</strong> Major GC is Mark-Compact. Objects start white, become grey when discovered, and turn black once their fields have been scanned. Scanning a grey object greys everything it references, so an object stays alive by being reachable at <em>any</em> depth, not by being named directly by a root. The invariant that no black object points to a white one is what guarantees nothing live is missed. The animation walks this one edge at a time, which is the part flat diagrams never show.</p>

<p><strong>Sweep and compact are different phases.</strong> Sweeping adds the gaps left by dead objects in the paged spaces to the free-lists. Unreachable large objects are reclaimed in that same phase, but by releasing their pages outright rather than through a free-list. Compaction is selective: V8 evacuates live objects off its most fragmented pages onto fresh ones. Large objects are never relocated, so they are freed in the sweep but are never part of compaction.</p>

<p><strong>Orinoco shrinks pauses, it does not remove them.</strong> Incremental marking splits work into small scheduled steps, concurrent marking runs on helper threads while JavaScript executes, and parallel collection uses several threads to finish the unavoidable pauses faster. V8’s write-barrier machinery is what makes that safe, and it serves at least three purposes: recording old-to-young references in remembered sets for the minor GC, preserving the marking invariant so concurrent marking cannot miss an object that becomes reachable mid-flight, and recording old-to-old slots that will need their pointers updated after compaction moves things.</p>

<p>One heap per isolate. That fact is what makes the second half make sense.</p>

<h2 id="the-node-event-loop">The Node event loop</h2>

<div class="interactive-explainer">
  <iframe src="https://mouaad.aallam.com/assets/files/v8-memory-and-the-node-event-loop/node-concurrency.html" title="Interactive explainer: how Node.js runs your code" loading="lazy" allowfullscreen=""></iframe>
  <div class="interactive-explainer-mobile">
    <span class="interactive-explainer-mobile__eyebrow">Interactive diagram</span>
    <strong>Explore how Node.js runs your code</strong>
    <span>Open the guided animation in a full-screen, mobile-friendly view.</span>
    <a href="https://mouaad.aallam.com/assets/files/v8-memory-and-the-node-event-loop/node-concurrency.html">Open interactive diagram <span aria-hidden="true">→</span></a>
  </div>
</div>

<p>Node runs your JavaScript on one thread. Everything else is about how work reaches that thread.</p>

<p><strong>The phase order moved.</strong> This is the one worth double-checking against whatever you already believe. Since <strong>libuv 1.45</strong>, which landed in <strong>Node 20.3.0</strong> (Node 20.0 through 20.2 still carried libuv 1.44.2 and ran timers first), a loop iteration runs:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pending → idle/prepare → poll → check → close → timers
</code></pre></div></div>

<p>Timers run at the <em>end</em> of an iteration, not the start, and a compatibility timer pass runs each time the loop is entered in default mode. Note also that <code class="language-plaintext highlighter-rouge">pending</code> gets a second turn right after poll, up to eight times, to avoid starving that queue.</p>

<p>Most third-party diagrams still show timers first. Node’s own guide has since been corrected and now documents the change explicitly, with timers appearing twice in its cycle diagram.</p>

<p>Drawn as an endless cycle the phase sequence looks unchanged, but do not read that as “nothing happens differently”. The move is observable. A <code class="language-plaintext highlighter-rouge">setTimeout(0)</code> scheduled from inside an I/O callback used to wait for the next iteration’s timers phase; now the timers phase is still ahead of it in the <em>same</em> iteration, so it can fire without another trip through poll. Node’s guide says as much: the change can affect how timers and <code class="language-plaintext highlighter-rouge">setImmediate</code> interact.</p>

<p><strong>Where the waiting happens.</strong> The loop can wait in the poll phase when nothing is immediately runnable but the loop is still <em>alive</em>, meaning it holds referenced handles or requests. Note that liveness is not only sockets: a pending timer is itself an active handle and will keep the loop waiting. The wait is bounded by the nearest timer deadline, or unbounded if no timer is armed. It does not wait at all if a <code class="language-plaintext highlighter-rouge">setImmediate</code> is queued, which Node arranges with an idle handle whose only job is to stop the loop blocking. If nothing referenced remains, the loop exits and the process ends.</p>

<p>The usual folk version of this is “it blocks when there is nothing to do”. The empty-queue half is right; the “nothing to do” half is exactly wrong, because with no referenced work left the loop does not block, it exits.</p>

<p><strong>Two queues sit outside the phases.</strong> When a callback hands control back to Node, the <code class="language-plaintext highlighter-rouge">process.nextTick</code> queue drains completely, then V8’s microtask queue drains completely, before the loop advances. Since Node 11 this happens between individual timer and immediate callbacks too, not only between phases.</p>

<p>Both names are traps. <code class="language-plaintext highlighter-rouge">process.nextTick</code> does <strong>not</strong> wait for the next iteration; it runs before the loop advances at all. <code class="language-plaintext highlighter-rouge">setImmediate</code> targets the <strong>check</strong> phase right after poll, which may still be ahead of you in the current iteration rather than the next one, depending on where you scheduled it. And the nextTick-before-promises rule holds at a CommonJS callback boundary but <strong>inverts in top-level ESM</strong>, where the module body is itself evaluated inside a microtask drain, so promise callbacks scheduled there run before <code class="language-plaintext highlighter-rouge">nextTick</code>.</p>

<p><strong>What actually uses the thread pool.</strong> Most async <code class="language-plaintext highlighter-rouge">fs</code>, <code class="language-plaintext highlighter-rouge">dns.lookup()</code>, async <code class="language-plaintext highlighter-rouge">zlib</code>, and specific crypto calls such as <code class="language-plaintext highlighter-rouge">pbkdf2</code>, <code class="language-plaintext highlighter-rouge">scrypt</code>, <code class="language-plaintext highlighter-rouge">randomBytes</code> and key generation. Native addons can queue work there too. Socket readiness does <strong>not</strong> use it, and neither does <code class="language-plaintext highlighter-rouge">dns.resolve*()</code>, which does its own network queries. This is why Node can hold tens of thousands of connections even though the pool has only four threads. Do not conclude that network code never touches the pool though: anything connecting by hostname usually goes through <code class="language-plaintext highlighter-rouge">dns.lookup()</code> first, so name resolution can contend for those same four threads.</p>

<p>The pool defaults to 4, is capped at 1024, and is set by <code class="language-plaintext highlighter-rouge">UV_THREADPOOL_SIZE</code> before the process starts. It is <strong>process-global</strong>: every event loop in the process, worker threads included, shares the same threads. Spawning workers does not multiply it. Fire more pool-backed work than there are threads and it queues, and one long task effectively shrinks the pool by one.</p>

<p><strong>Three unrelated sets of threads</strong> get conflated constantly: V8’s own GC and JIT helpers, libuv’s process-global pool of four, and any worker threads you spawn. Only the last runs your JavaScript.</p>

<p><strong>Workers are isolates, not processes.</strong> Each worker gets its own V8 isolate, heap, event loop, and pair of queues, so ordinary objects can never be shared. For payload memory there are three choices: <code class="language-plaintext highlighter-rouge">postMessage</code> structured-clones a copy, a transfer list moves an <code class="language-plaintext highlighter-rouge">ArrayBuffer</code>’s ownership with no copy, and a <code class="language-plaintext highlighter-rouge">SharedArrayBuffer</code> maps the same bytes into both isolates with <code class="language-plaintext highlighter-rouge">Atomics</code> to coordinate. Transfer lists can also hand over resources such as a <code class="language-plaintext highlighter-rouge">MessagePort</code> or a <code class="language-plaintext highlighter-rouge">FileHandle</code>. Separate heaps also means separate GC, so a worker’s collection does not pause the main thread.</p>

<p>Workers are not a full isolation boundary though. An uncaught exception terminates that worker and emits <code class="language-plaintext highlighter-rouge">error</code> on its parent-side <code class="language-plaintext highlighter-rouge">Worker</code> object, and the parent survives <em>only if it handles that event</em>: an unhandled <code class="language-plaintext highlighter-rouge">error</code> on an <code class="language-plaintext highlighter-rouge">EventEmitter</code> is thrown and will take the process with it. A native fault or a global OOM takes everything down regardless. <code class="language-plaintext highlighter-rouge">resourceLimits</code> caps selected per-worker JS-engine resources rather than the worker’s total memory, and notably excludes external data such as <code class="language-plaintext highlighter-rouge">ArrayBuffer</code> backing stores, which loops back to the external-memory point above.</p>

<p><strong>Processes are the real boundary.</strong> With <code class="language-plaintext highlighter-rouge">cluster</code>, a primary process forks however many workers you ask for, commonly one per <code class="language-plaintext highlighter-rouge">os.availableParallelism()</code>. Under the default off-Windows <code class="language-plaintext highlighter-rouge">SCHED_RR</code> policy the primary owns the listening socket and hands accepted connections to workers over IPC; Windows lets the OS distribute them instead. Each process gets its own isolate, heap, event loop and <code class="language-plaintext highlighter-rouge">--max-old-space-size</code> budget, so a GC pause in one never stalls another. They still share OS resources such as files, sockets and system limits, so the isolation is strong but not absolute.</p>

<h2 id="where-the-two-halves-meet">Where the two halves meet</h2>

<p>The reason to care about Orinoco is that in Node a stop-the-world GC pause lands on the event loop. Callbacks queued on <em>that isolate’s</em> loop wait behind it, exactly as they would behind a synchronous <code class="language-plaintext highlighter-rouge">JSON.parse</code> of something enormous. Other worker isolates and other processes keep running, and concurrent marking is not itself a pause. Still, the list of things that block your loop is not just your own slow code; it includes the collector.</p>

<p>Which also explains why the process-per-core shape is more than a throughput trick. N processes means N independent heaps, each collected on its own schedule, so one process pausing to collect does not stall the others. Worker threads give you the same separation of heaps inside a single process, at the cost of sharing that process’s fate.</p>

<p>One closing warning. The phase order is the detail most likely to be stale in your head, because the diagram everyone memorised outlived the implementation by several major versions. Widely repeated diagrams drift, and so do assumptions about which sources have caught up. Reading <code class="language-plaintext highlighter-rouge">uv_run()</code> settles it in about a minute.</p>]]></content>
      

      
      
      
      
      

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

      
        
      

      
        <category term="V8" />
      
        <category term="Node.js" />
      
        <category term="Garbage Collection" />
      
        <category term="Event Loop" />
      

      
      
        <summary type="html"><![CDATA[How V8 manages memory and how Node schedules work, with two interactive animations covering heap spaces, the Scavenger, Mark-Compact, the event loop phases, the libuv thread pool, workers and process isolation.]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mouaad.aallam.com/assets/images/generated/posts/2026-07-28-v8-memory-and-the-node-event-loop.png" />
        <media:content medium="image" url="https://mouaad.aallam.com/assets/images/generated/posts/2026-07-28-v8-memory-and-the-node-event-loop.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
    <entry>
      

      <title type="html">Writing Libraries Is Writing Contracts</title>
      <link href="https://mouaad.aallam.com/writing-libraries-is-writing-contracts/" rel="alternate" type="text/html" title="Writing Libraries Is Writing Contracts" />
      <published>2026-05-09T10:00:00+00:00</published>
      <updated>2026-05-09T10:00:00+00:00</updated>
      <id>https://mouaad.aallam.com/writing-libraries-is-writing-contracts</id>
      
      
        <content type="html" xml:base="https://mouaad.aallam.com/writing-libraries-is-writing-contracts/"><![CDATA[<p>Writing a library starts with code, but maintaining one is mostly about contracts.</p>

<p>Every public function, type, default value, error message, dependency, and example becomes something users can build on. Once they do, changing it is no longer a private refactor. It is a negotiation with people who are trying to keep their own systems working.</p>

<p>That is the part that took me time to appreciate. A library can be small, elegant, and well-tested, but the moment it has users, its shape matters beyond its implementation. The API becomes a promise. The docs become a promise. The release process becomes a promise. Even the things you choose not to expose become part of how users understand the library.</p>

<p>I have felt this across different kinds of projects: a larger API client such as <a href="https://github.com/aallam/openai-kotlin"><code class="language-plaintext highlighter-rouge">openai-kotlin</code></a>, smaller focused Kotlin libraries, and newer runtime-boundary work like <a href="https://github.com/aallam/execbox"><code class="language-plaintext highlighter-rouge">execbox</code></a>. The details are different, but the maintenance pressure is the same: once people depend on your library, you are not only publishing code. You are publishing expectations.</p>

<div class="text-center">
  <p><img src="https://mouaad.aallam.com/assets/images/blog/library_contract.svg" alt="Library contracts between maintainers and users" width="90%" /></p>
</div>

<h2 id="public-api-is-more-than-types">Public API is more than types</h2>

<p>It is tempting to think of public API as the list of exported symbols. Functions, classes, interfaces, modules, packages. That is only the visible part.</p>

<p>The real API also includes behavior:</p>

<ul>
  <li>what happens when input is missing,</li>
  <li>whether calls are lazy or eager,</li>
  <li>which errors are thrown and when,</li>
  <li>whether ordering is stable,</li>
  <li>how cancellation works,</li>
  <li>how retries, timeouts, and defaults behave,</li>
  <li>which platforms are supported,</li>
  <li>which values are accepted even if the type allows more.</li>
</ul>

<p>Users learn those details from your implementation, docs, examples, and tests. If the behavior is useful, they will depend on it. If the behavior is accidental, they may still depend on it.</p>

<p>This is why library code needs a different level of care than application code. In an application, an internal function can be fixed when its caller changes. In a library, you do not control the callers. They live in other repositories, other companies, other release cycles, and sometimes other time zones. You only see them when an issue appears.</p>

<p>The harder part is that users rarely depend on your API exactly the way you imagined. They will compose it with frameworks you do not use, run it on platforms you do not test every day, and rely on edge cases because those edge cases solve real problems for them.</p>

<p>That does not mean every behavior must be frozen forever. It means public behavior should be intentional. If something is not meant to be stable, do not expose it casually. If something is stable, test it like a contract.</p>

<h2 id="small-surfaces-survive">Small surfaces survive</h2>

<p>The easiest API to maintain is the one you did not publish.</p>

<p>This sounds obvious, but it is one of the most useful lessons in library design. Every public helper, option, overload, type alias, package path, and configuration hook creates future work. It may need documentation. It may need tests. It may need compatibility. It may limit a future internal design.</p>

<p>Small public surfaces are not about minimalism for its own sake. They are about preserving room to improve the library without breaking users.</p>

<p>A good library usually has more internal machinery than public API. That is fine. Internals can be ugly for a while. They can be renamed, split, optimized, generated, deleted, or replaced. Public API has a different cost model. Once it exists, removal is expensive.</p>

<p>This is especially important when a project is young. Early versions are full of uncertainty. You may not know the right abstractions yet. You may not know whether users need a low-level primitive or a higher-level workflow. Publishing too much too early turns guesses into obligations.</p>

<p>I saw this while preparing <code class="language-plaintext highlighter-rouge">execbox</code> for a stable library surface. Experimental runtime packages had accumulated around the core idea, so I removed them before 1.0 and kept two supported responsibilities: provider contracts in <code class="language-plaintext highlighter-rouge">@execbox/core</code> and QuickJS execution in <code class="language-plaintext highlighter-rouge">@execbox/quickjs</code>. That cleanup was disruptive in the short term, but it made the public promise smaller and clearer.</p>

<p>The better default is to expose the smallest useful path, then let real usage pull more surface area out of the internals. When a pattern repeats, promote it. When users keep reaching around the API, understand why. When an option exists only because the implementation happened to have it, keep it private.</p>

<p>Small surfaces also make documentation and examples better. A library that can be explained with a few concepts is easier to adopt, easier to debug, and easier to trust.</p>

<h2 id="docs-are-part-of-the-contract">Docs are part of the contract</h2>

<p>Documentation is not a decoration around the library. For many users, it is the library.</p>

<p>The first example teaches them what the maintainers consider normal. The getting-started page defines the happy path. The advanced guide tells them which use cases are expected. The upgrade guide tells them whether changes are predictable. Missing docs tell them where the contract is weak.</p>

<p>This is why examples matter so much. Users copy them. They build habits from them. If the example skips error handling, people will skip error handling. If it uses an unstable internal helper, people will use that helper. If it shows a pattern that only works in a narrow environment, users will assume the library failed when it does not work elsewhere.</p>

<p>Docs also help maintainers make decisions. If a behavior cannot be explained clearly, the API may be wrong. If a feature needs five paragraphs of caveats, it may be too complex, too early, or sitting at the wrong abstraction level. If the docs keep saying what the library does not do, the project may not have a clear enough positive shape yet.</p>

<p>The best docs do not need to cover every implementation detail. They need to make the contract legible:</p>

<ul>
  <li>what the library is for,</li>
  <li>what the main path looks like,</li>
  <li>which guarantees users can rely on,</li>
  <li>where the boundaries are,</li>
  <li>how to upgrade when those boundaries move.</li>
</ul>

<p>In practice, docs and design feed each other. Writing the docs often exposes where the API is too clever, where a type name is vague, or where a feature has no obvious place in the mental model.</p>

<h2 id="compatibility-is-a-budget">Compatibility is a budget</h2>

<p>Compatibility is not binary. It is a budget you spend.</p>

<p>Every breaking change spends user trust. Sometimes that spend is worth it. Bad APIs should not live forever just because they were published once. A confusing abstraction can cost users more over time than a well-explained migration. Pre-1.0 libraries especially need room to correct their shape before stability hardens the wrong design.</p>

<p>But breaking changes should be honest. They should solve a real problem, not clean up maintainer discomfort. They should come with migration notes. They should avoid surprising users with unrelated churn. They should be grouped carefully instead of scattered across releases without a story.</p>

<p>Deprecation is useful when it gives users time to move. It is less useful when it becomes a permanent museum of old ideas. A deprecation should answer three questions:</p>

<ul>
  <li>what should users do instead,</li>
  <li>when does the old path go away,</li>
  <li>why is the change worth making.</li>
</ul>

<p>For projects that follow Semantic Versioning, version numbers help here, but they are not enough by themselves. SemVer treats the public API as unstable during <code class="language-plaintext highlighter-rouge">0.y.z</code> and uses major-version changes after <code class="language-plaintext highlighter-rouge">1.0</code> to signal incompatible API changes. Neither signal tells users whether the change is understandable, whether the migration is realistic, or whether the maintainers respect their time.</p>

<p>Compatibility also includes softer promises: supported platforms, runtime versions, generated code shape, dependency ranges, serialization formats, package names, module paths, and error semantics. These are easy to treat as implementation details until users build on them.</p>

<p>The maintainer’s job is not to avoid all change. It is to make change predictable.</p>

<h2 id="dependencies-become-user-dependencies">Dependencies become user dependencies</h2>

<p>Every runtime dependency you expose, including its transitive dependencies, becomes part of someone else’s application.</p>

<p>That does not mean libraries should have no dependencies. Good dependencies can reduce bugs, improve standards compliance, and let maintainers focus on the library’s actual purpose. But dependencies carry costs that are different in a library than in an application.</p>

<p>An application chooses its own runtime, deployment target, bundle size, dependency policy, and upgrade schedule. A library is pulled into environments it does not control. A transitive dependency can affect build time, binary size, cold start, platform support, security reviews, licensing, and version resolution.</p>

<p>The question is not “can this dependency help?” The question is “is this dependency part of the contract I want users to inherit?”</p>

<p>Sometimes the answer is yes. Sometimes the answer is no. Sometimes the right design is to keep an integration optional, put it behind a separate package, or accept a little more local code to avoid forcing a large dependency onto every user.</p>

<p>Dependencies also shape maintenance. If your library wraps a fast-moving API, generated models or protocol clients may be necessary. If your library targets multiple platforms, dependency choices can decide which platforms remain possible. If your library sits close to runtime boundaries, dependency behavior can leak into security, lifecycle, or performance expectations.</p>

<p>The dependency tree is not invisible. Users will feel it.</p>

<h2 id="maintenance-is-product-work">Maintenance is product work</h2>

<p>Maintaining a library is product work under technical constraints.</p>

<p>The product is not a UI. It is the experience of adopting, understanding, upgrading, debugging, and trusting the library. Issues, pull requests, release notes, examples, CI, package metadata, and error messages are all part of that experience.</p>

<p>This is where taste matters, but not in the vague sense. Taste is choosing boring names when clever names would be memorable. It is saying no to an option that would make one user happy but weaken the model for everyone. It is keeping a release small enough that users can understand it. It is accepting that a missing feature is sometimes better than a feature with the wrong contract.</p>

<p>A maintainer has to balance different kinds of pressure:</p>

<ul>
  <li>new users want the simplest possible start,</li>
  <li>advanced users want escape hatches,</li>
  <li>contributors want their use cases accepted,</li>
  <li>existing users want stability,</li>
  <li>the maintainer wants the codebase to remain workable.</li>
</ul>

<p>Those goals conflict. A healthy library does not satisfy all of them equally. It chooses a center of gravity and makes that choice visible.</p>

<p>For me, this is the main difference between writing code and writing libraries. Code can be correct in isolation. A library has to be correct in relation to users. It has to age. It has to carry old decisions until they can be changed responsibly. It has to leave enough space for future maintenance.</p>

<h2 id="the-quiet-goal">The quiet goal</h2>

<p>The quiet goal of a library is predictability.</p>

<p>Users should be able to predict how the API behaves. They should be able to predict whether an upgrade is risky. They should be able to predict where to look when something fails. They should be able to predict whether a feature belongs in the library or outside it.</p>

<p>That predictability does not happen by accident. It comes from treating the public surface as a contract, keeping that contract small, documenting it clearly, changing it deliberately, and remembering that every dependency and release is part of the user’s system too.</p>

<p>Reusable code is the beginning. The real work is making it safe for other people to build on.</p>]]></content>
      

      
      
      
      
      

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

      
        
      

      
        <category term="Libraries" />
      
        <category term="Open Source" />
      
        <category term="Software Engineering" />
      

      
      
        <summary type="html"><![CDATA[What maintaining open source libraries teaches about API design, documentation, compatibility, dependencies, releases, and user trust.]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mouaad.aallam.com/assets/images/generated/posts/2026-05-09-writing-libraries-is-writing-contracts.png" />
        <media:content medium="image" url="https://mouaad.aallam.com/assets/images/generated/posts/2026-05-09-writing-libraries-is-writing-contracts.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
    <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 useful shift happening in agent systems that use MCP: instead of asking the model to call one tool at a time, let it write small programs that call tools inside a controlled execution environment.</p>

<p>That changes the shape of the system. Tool definitions do not all have to sit in the model context. Intermediate results do not all have to be replayed through the model. Multi-step logic can run closer to the data it is manipulating.</p>

<p>This is the pattern <a href="https://github.com/aallam/execbox"><code class="language-plaintext highlighter-rouge">execbox</code></a> is built around: a reusable Node.js library layer for exposing host-defined tools and wrapped MCP servers to guest JavaScript, while keeping capability and runtime boundaries explicit.</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>Direct MCP tool loops are a good default. The client exposes tools, the model picks one, the host executes it, the result goes back into context, and the model decides what to do next.</p>

<p>That loop is simple, but an eager implementation scales poorly once the tool catalog or intermediate data gets large:</p>

<ul>
  <li>every tool definition exposed up front consumes context,</li>
  <li>every intermediate result passes back through the model,</li>
  <li>large payloads are copied and summarized repeatedly,</li>
  <li>multi-step control flow becomes token-heavy.</li>
</ul>

<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>

<p>For tools that return large documents, search results, database rows, logs, or API payloads, the loop spends too much of the model budget on mechanical data movement. A compact programming surface lets the model call tool-like APIs, filter intermediate values locally, and return only the final result the host needs to see.</p>

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

<p>Posts from Anthropic and Cloudflare, along with the MCP client best practices, describe the same architecture pressure.</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>, frames direct MCP usage around two scaling problems: tool definitions consume context, and intermediate results consume more context. Their answer is to let the model write code against tool-like APIs, load definitions on demand, and keep intermediate processing inside the execution environment.</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 the API side: a large tool surface can become a smaller typed SDK surface that the model uses from generated code. Cloudflare then followed with <a href="https://blog.cloudflare.com/dynamic-workers/">Sandboxing AI agents, 100x faster</a>, focused on where generated code should run.</p>

<p>The MCP docs call this pattern <a href="https://modelcontextprotocol.io/docs/develop/clients/client-best-practices#programmatic-tool-calling-/-code-mode">Programmatic Tool Calling / Code Mode</a>: the model writes code, the code runs in a sandbox, and the host brokers MCP tool calls so only the final result needs to return to the model.</p>

<p>The two scaling pressures have related but distinct answers. Progressive discovery controls which tool definitions enter the model context, while programmatic tool calling controls how tools are invoked and where intermediate results are processed. They can be used independently or together.</p>

<p>Together, these posts and docs point in the same direction: eager direct tool calling is useful but expensive at scale, code execution can compress data movement, and the runtime cannot be an afterthought.</p>

<h2 id="execbox">Execbox</h2>

<p><code class="language-plaintext highlighter-rouge">execbox</code> is the library layer I wanted for that pattern. It is not an agent framework or hosted sandbox product; it is a set of Node.js packages that turn host capabilities into callable guest namespaces, then run guest JavaScript against those namespaces through a chosen executor.</p>

<p>The package map is intentionally small: <code class="language-plaintext highlighter-rouge">@execbox/core</code> owns the execution contract, provider resolution, and MCP adapters; <code class="language-plaintext highlighter-rouge">@execbox/quickjs</code> provides inline and worker-hosted QuickJS execution.</p>

<p>The core flow stays the same across those packages: host code defines tools or discovers them from MCP, those tools become a deterministic guest namespace, guest code runs against that namespace, tool calls cross a host-controlled boundary, and results come back as JSON-compatible data. The same guest code shape can start with inline QuickJS and move to worker-hosted QuickJS without changing the provider contract.</p>

<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>MCP can appear on either side of the flow. Upstream MCP servers can be wrapped into guest namespaces, and execbox can also expose code execution itself as an MCP server so a client gets a compact code-running surface instead of a large direct tool catalog.</p>

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

<p>In TypeScript, a typical MCP provider flow starts with an MCP server declared through the MCP SDK, then wraps it as an execbox provider.</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="k">try</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>

  <span class="k">if </span><span class="p">(</span><span class="o">!</span><span class="nx">result</span><span class="p">.</span><span class="nx">ok</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">throw</span> <span class="k">new</span> <span class="nc">Error</span><span class="p">(</span><span class="nx">result</span><span class="p">.</span><span class="nx">error</span><span class="p">.</span><span class="nx">message</span><span class="p">);</span>
  <span class="p">}</span>

  <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="nx">result</span><span class="p">.</span><span class="nx">result</span><span class="p">);</span>
<span class="p">}</span> <span class="k">finally</span> <span class="p">{</span>
  <span class="k">await</span> <span class="nx">handle</span><span class="p">.</span><span class="nf">close</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The runtime choice is separate from the provider shape. Use inline QuickJS for trusted, lowest-friction local execution. Use worker-hosted QuickJS when you want local execution off the main thread with worker lifecycle controls. Both use the same provider and execution contracts; the worker changes runtime placement and lifecycle, not the capability set.</p>

<h2 id="boundaries">Boundaries</h2>

<p>The runtime does not own the capabilities. The provider and exposed tool surface define them.</p>

<p>If guest code can call a tool that deletes data, sends email, or reaches a private system, then guest code has that authority. Moving execution from inline QuickJS to a worker changes lifecycle and runtime placement, not what the exposed tools are allowed to do.</p>

<p>That capability boundary is not a runtime authorization decision. The host still needs to evaluate each sandbox-originated tool call against the applicable user confirmation or categorical grant. Approving a generated script should not automatically authorize every call it makes.</p>

<p>Execbox helps make that execution path controlled: fresh execution state per call, JSON-only tool and result boundaries, schema validation around host tool execution, bounded logs, timeout and memory controls, and abort propagation into in-flight host work.</p>

<p>Those controls matter, but they do not make a dangerous tool safe to expose. They make it easier to expose only the tools you intend, run generated code through a stable contract, and choose the runtime placement that matches the deployment.</p>

<p>That is the role of <code class="language-plaintext highlighter-rouge">execbox</code>: keep one capability model, support MCP tools and wrapped MCP servers, and let applications choose between inline and worker-hosted QuickJS without rewriting the guest/tool contract.</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 helps AI agents using MCP scale beyond direct tool loops, and how execbox keeps capability and runtime boundaries explicit.]]></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>
