<?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://aallam.com/feed.xml" rel="self" type="application/atom+xml" />
  <link href="https://aallam.com/" rel="alternate" type="text/html" />
  <updated>2026-12-05T12:34:00+00:00</updated>
  <id>https://aallam.com/feed.xml</id>

  
  
  

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

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

  

  
  
  
  
  
  
  
    <entry>
      

      <title type="html">V8 Memory and the Node Event Loop</title>
      <link href="https://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://aallam.com/v8-memory-and-the-node-event-loop</id>
      
      
        <content type="html" xml:base="https://aallam.com/v8-memory-and-the-node-event-loop/"><![CDATA[<p>These are my notes on V8 memory and the Node event loop. A garbage-collection pause delays callbacks on the JavaScript thread, much like long synchronous code. The event loop can also wait for I/O when no callback is ready. That wait does not occupy the JavaScript thread.</p>

<p>Two interactive animations explain the details. Each offers a guided tour and a free mode for trying operations.</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://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://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 animation shows a simplified heap layout, using the Scavenger to collect young objects. V8 versions and build options can use other layouts or collectors.</p>

<p>Most new objects start in <strong>New space</strong>, split into two halves. A <strong>bump pointer</strong> marks the next free position and advances as objects are added. Objects that survive collections can move to <strong>Old space</strong>. Large objects use separate spaces, while some allocation sites send objects straight to Old space, a choice called <strong>pretenuring</strong>. <strong>Code space</strong> holds generated machine code, and <strong>Read-only space</strong> holds fixed runtime data.</p>

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

<p><strong>Heap size is only part of memory use.</strong> Small integers can be stored directly in a value, without a separate heap object. The bytes behind <code class="language-plaintext highlighter-rouge">ArrayBuffer</code> and Node <code class="language-plaintext highlighter-rouge">Buffer</code> objects live outside V8’s managed heap, so <code class="language-plaintext highlighter-rouge">--max-old-space-size</code> does not limit them. <code class="language-plaintext highlighter-rouge">process.memoryUsage().arrayBuffers</code> reports those bytes as part of the broader <code class="language-plaintext highlighter-rouge">external</code> figure. Check them when process memory grows while the JavaScript heap stays steady.</p>

<p><strong>Minor GC copies the survivors.</strong> The Scavenger finds live young objects through roots and recorded references from older objects. It copies survivors to the other half of New space or promotes them to Old space, then flips the halves. It does not copy dead objects.</p>

<p>Copying work depends on how much survives. More allocation still fills the space sooner and causes more collections. JavaScript pauses during a scavenge, even when helper threads share the work.</p>

<p><strong>Surviving twice is a rule of thumb.</strong> In this model, an object that survives a second scavenge usually moves to Old space. V8 uses an age mark to distinguish objects kept by the previous scavenge from newer allocations. It does not need a counter on each object. Space pressure can move survivors earlier. Pretenuring is different: it puts an object in Old space from the start.</p>

<p><strong>Marking follows chains of references.</strong> V8’s major collector, Mark-Compact, starts from roots such as references on the stack. In the three-color model, white means unseen, grey means found but not yet scanned, and black means scanned. Scanning follows references to other objects. If a root reaches A, A reaches B, and B reaches C, all three stay alive. The animation follows those links one at a time.</p>

<p><strong>Sweeping frees space. Compaction moves objects.</strong> Sweeping makes dead objects’ memory available for reuse. Compaction moves live objects from selected pages to reduce gaps. This compaction step does not move large objects. Their pages can be freed when they become unreachable.</p>

<p><strong>Orinoco reduces pauses.</strong> V8 reduces pauses in three ways. Incremental marking takes small steps between JavaScript work. Concurrent marking uses helper threads while JavaScript runs. Parallel collection uses several threads during a pause. Some pauses remain.</p>

<p>V8 tracks reference changes with <strong>write barriers</strong>, small checks made when code stores a reference. They record links from old objects to young ones, keep marking safe while JavaScript changes objects, and record references that need updating after objects move.</p>

<p>An <strong>isolate</strong> is a separate V8 engine instance with its own JavaScript heap. That matters when we get to worker threads.</p>

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

<div class="interactive-explainer">
  <iframe src="https://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://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>By default, Node runs your JavaScript on one main thread. The event loop selects the next callback. Workers can run JavaScript on other threads.</p>

<p><strong>Timers moved to the end of an iteration.</strong> Starting with libuv 1.45, included in <a href="https://nodejs.org/en/blog/release/v20.3.0">Node 20.3.0</a>, the main phases run in this order:</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>There is also a timer pass before entering the loop in default mode, kept for compatibility. Some pending callbacks get another turn right after poll. The <a href="https://github.com/libuv/libuv/blob/v1.45.0/src/unix/core.c">libuv source</a> shows these extra steps.</p>

<p>The <a href="https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick">Node event-loop guide</a> explains the change. Do not read the phase list above as a timing guarantee: <code class="language-plaintext highlighter-rouge">setTimeout(fn, 0)</code> has a minimum delay of 1 ms and runs only once it is due. When scheduled together inside an I/O callback, <code class="language-plaintext highlighter-rouge">setImmediate</code> runs before that timer. In older versions, timers ran at the start of the next iteration, before another pass through poll.</p>

<p><strong>Where the waiting happens.</strong> Poll can wait for I/O when no callback is ready but work still keeps the loop alive.</p>

<p>That includes referenced timers as well as sockets and requests. The next timer limits how long poll can wait. A queued <code class="language-plaintext highlighter-rouge">setImmediate</code> prevents that wait. Once nothing keeps the loop alive, it exits. Node can then end the process, unless a <code class="language-plaintext highlighter-rouge">beforeExit</code> handler schedules more work.</p>

<p><strong>Two queues run between callbacks.</strong> At a normal callback boundary, Node runs queued <code class="language-plaintext highlighter-rouge">process.nextTick</code> callbacks, then V8 microtasks such as Promise callbacks. This also happens between individual timer and immediate callbacks. Work added to these queues can keep them running, so repeatedly scheduling more can delay I/O.</p>

<p>The names can mislead. <code class="language-plaintext highlighter-rouge">process.nextTick</code> does not wait for the next loop iteration. <code class="language-plaintext highlighter-rouge">setImmediate</code> runs in the check phase, which may still be ahead in the current iteration. Top-level ES module code is an exception. It runs as a microtask, so Promise callbacks scheduled there run before <code class="language-plaintext highlighter-rouge">nextTick</code> callbacks scheduled there.</p>

<p><strong>What uses the thread pool.</strong> Most async <code class="language-plaintext highlighter-rouge">fs</code> operations, <code class="language-plaintext highlighter-rouge">dns.lookup()</code>, async <code class="language-plaintext highlighter-rouge">zlib</code>, and async forms of 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 use it. Native addons can queue work there too. Socket I/O does not use the pool, and neither does <code class="language-plaintext highlighter-rouge">dns.resolve*()</code>, which makes its own network queries. A connection by hostname usually calls <code class="language-plaintext highlighter-rouge">dns.lookup()</code> first. That lookup can wait for the pool.</p>

<p>The pool defaults to 4 threads, with a maximum of 1024. Set <code class="language-plaintext highlighter-rouge">UV_THREADPOOL_SIZE</code> before starting the process to change it. Every event loop in the process shares this pool, including worker threads. Starting workers does not add pool capacity. When all pool threads are busy, more work has to wait.</p>

<p>Keep three groups separate: V8’s GC and compiler helpers, libuv’s pool, and the worker threads you create. Of these, only worker threads run your JavaScript.</p>

<p><strong>Workers have separate JavaScript heaps.</strong> Each worker has its own V8 isolate, event loop, and callback queues. Sending a normal object with <code class="language-plaintext highlighter-rouge">postMessage</code> copies it using structured cloning. A transfer list moves a transferable <code class="language-plaintext highlighter-rouge">ArrayBuffer</code> without copying its bytes. The sender then loses access to that buffer.</p>

<p>Some buffers, including Node’s internal Buffer pool, cannot be transferred. A <code class="language-plaintext highlighter-rouge">SharedArrayBuffer</code> lets workers access the same bytes. Use <code class="language-plaintext highlighter-rouge">Atomics</code> to coordinate access.</p>

<p>Transfer lists can also move resources such as a <code class="language-plaintext highlighter-rouge">MessagePort</code> or <code class="language-plaintext highlighter-rouge">FileHandle</code>.</p>

<p>Workers share the process’s risks. An uncaught exception stops 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. Handle that event in the parent. Otherwise, it becomes an uncaught error there too. A native crash or process-wide out-of-memory failure can stop everything. <code class="language-plaintext highlighter-rouge">resourceLimits</code> limits selected V8 resources, not total worker memory, and excludes <code class="language-plaintext highlighter-rouge">ArrayBuffer</code> backing stores.</p>

<p><strong>Processes give stronger isolation.</strong> With <code class="language-plaintext highlighter-rouge">cluster</code>, a primary process forks workers, often using <code class="language-plaintext highlighter-rouge">os.availableParallelism()</code> to choose how many. By default, the primary distributes connections on platforms other than Windows. On Windows, workers normally accept from a shared listening socket. Each process has its own heap, event loop, and <code class="language-plaintext highlighter-rouge">--max-old-space-size</code> limit. A GC pause in one does not directly pause another, though they still compete for CPU and system memory.</p>

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

<p>When GC pauses an isolate’s JavaScript thread, callbacks on its loop wait, just as they would during a large synchronous <code class="language-plaintext highlighter-rouge">JSON.parse</code>. Concurrent marking is different: JavaScript can keep running while helper threads mark objects. Memory use and allocation rate therefore matter when investigating slow callbacks, alongside the application code itself.</p>

<p>Separate processes have independent heaps and collection schedules. Workers also give you separate JavaScript heaps within one process, but share the process’s total memory use and failure risks. Neither removes competition for the machine’s resources.</p>

<p>Check the docs for the Node version you run. Start with the event-loop guide. Read <code class="language-plaintext highlighter-rouge">uv_run()</code> when the exact order matters. The animations are learning models, not a trace of every V8 or libuv detail.</p>

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

<ul>
  <li><a href="https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick">The Node.js event loop</a></li>
  <li><a href="https://nodejs.org/en/blog/release/v20.3.0">Node 20.3.0 release notes</a></li>
  <li><a href="https://github.com/libuv/libuv/blob/v1.45.0/src/unix/core.c">libuv 1.45 event-loop implementation</a></li>
  <li><a href="https://docs.libuv.org/en/v1.x/threadpool.html">libuv thread pool</a></li>
  <li><a href="https://nodejs.org/api/worker_threads.html">Node worker threads and resource limits</a></li>
  <li><a href="https://nodejs.org/api/process.html#processmemoryusage">Node process memory usage</a></li>
  <li><a href="https://nodejs.org/api/cluster.html#how-it-works">Node cluster scheduling</a></li>
  <li><a href="https://v8.dev/blog/trash-talk">V8’s Orinoco garbage collector</a></li>
  <li><a href="https://v8.dev/blog/concurrent-marking">Concurrent marking in V8</a></li>
</ul>]]></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 runs callbacks, with interactive guides to garbage collection, the event loop, the thread pool, workers, and processes.]]></summary>
      

      
      
        
        <media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://aallam.com/assets/images/generated/posts/2026-07-28-v8-memory-and-the-node-event-loop.png" />
        <media:content medium="image" url="https://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://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://aallam.com/writing-libraries-is-writing-contracts</id>
      
      
        <content type="html" xml:base="https://aallam.com/writing-libraries-is-writing-contracts/"><![CDATA[<p>Writing a library starts with code, but maintaining one is mostly about contracts.</p>

<p>Users can build on every public function, type, default value, error message, dependency, and example. A change to any of them can force users to update their systems.</p>

<p>That took me time to appreciate. A library can be small and well tested. Once people use it, its design matters beyond its implementation. The API becomes a promise. The docs become a promise. The release process becomes a promise.</p>

<p>Even private parts shape what users expect the library to provide.</p>

<p>I have felt this while maintaining <a href="https://github.com/aallam/openai-kotlin"><code class="language-plaintext highlighter-rouge">openai-kotlin</code></a>, smaller Kotlin libraries, and <a href="https://github.com/aallam/execbox"><code class="language-plaintext highlighter-rouge">execbox</code></a>, which runs JavaScript with access to tools chosen by the host. The projects differ in size and purpose, but each has users whose code needs to keep working.</p>

<div class="text-center">
  <p><img src="https://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 functions, classes, interfaces, and packages a library exposes. 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 changes how you maintain the code. Within an application, you can often update an internal function and its callers together. With a library, you do not control the callers. They live in other repositories and follow other release schedules. You may only hear about them when something breaks.</p>

<p>Users rarely depend on your API exactly as you imagined. They combine it with unfamiliar frameworks and run it on platforms you may not test. They also rely on edge cases that 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="keep-the-public-api-small">Keep the public API small</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>A small public API leaves room to improve the library without breaking users.</p>

<p>A library can keep plenty of code private. That code can be renamed, split, optimized, or replaced without asking users to change anything. Removing a public API is harder because someone may already depend on it.</p>

<p>This matters most when a project is young. You may not yet know whether users need a small building block or a complete workflow. Publishing too much too early turns guesses into promises you have to keep.</p>

<p>I saw this while preparing <code class="language-plaintext highlighter-rouge">execbox</code> for a stable API. Experimental runtime packages had grown around the core idea, so I removed them before 1.0. I kept <code class="language-plaintext highlighter-rouge">@execbox/core</code> for execution and tool-provider interfaces. I kept <code class="language-plaintext highlighter-rouge">@execbox/quickjs</code> for running code in QuickJS. The cleanup caused short-term disruption. It reduced what users must learn and what I must support.</p>

<p>Start with the smallest useful API, then add to it when real usage shows a need. When users keep working around the API, find out why. An internal option does not need to become public just because it already exists.</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 shows the usual setup and first successful call. 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 is hard to explain, the API may need work. If a feature needs five paragraphs of exceptions, it may be doing too much. Writing down what the library is for can help decide which features belong in it.</p>

<p>The best docs do not need to cover every implementation detail. They need to make a few things clear:</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>Writing the docs often reveals a confusing API, a vague type name, or a feature that does not fit the rest of the library.</p>

<h2 id="make-upgrades-predictable">Make upgrades predictable</h2>

<p>Every breaking change asks users to spend time upgrading. Sometimes that work is worth it: a confusing API can cost more over time than a clear migration. Before 1.0, libraries especially need room to fix design mistakes.</p>

<p>A breaking change should solve a clear problem and come with migration notes. Keep unrelated changes out of the upgrade path, and explain why the work is worth doing.</p>

<p>Marking an API as deprecated gives users time to replace it before removal. The notice 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 <a href="https://semver.org/">Semantic Versioning</a>, version numbers help, but they are not enough. SemVer allows the public API to change during <code class="language-plaintext highlighter-rouge">0.y.z</code> and requires a major-version increase for incompatible API changes after <code class="language-plaintext highlighter-rouge">1.0</code>. Users still need to know what changed and how to update their code.</p>

<p>Compatibility also covers supported platforms, runtime versions, generated code, dependency versions, data formats, package names, module paths, and error behavior. These may look like internal details until users build on them.</p>

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

<p>When users install your library, they also inherit its required runtime dependencies and the packages those dependencies need.</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 runs in environments its maintainer does not control. A transitive dependency can affect build time, binary size, cold start, platform support, security reviews, licensing, and version resolution.</p>

<p>Ask whether the benefit is worth the cost to users. Sometimes it is. In other cases, an optional integration, a separate package, or a little more local code can spare users a dependency they do not need.</p>

<p>Dependencies also shape maintenance. An API client may need generated types to keep up with an API. A library supporting several platforms needs dependencies that work on those platforms. A library that runs other code needs to account for how its dependencies handle permissions, cleanup, and memory.</p>

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

<p>Maintaining a library includes helping people adopt, understand, upgrade, and debug it. Issues, pull requests, release notes, examples, CI, package metadata, and error messages are all part of that work.</p>

<p>That means choosing clear names and keeping releases easy to understand. Sometimes I turn down a feature that would make the API harder to use.</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 ways to handle unusual cases,</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 can conflict. Decide which uses the library supports best, and make that choice clear.</p>

<p>For me, this is the hard part of maintaining libraries. I must support old decisions while users migrate, yet leave room to improve the design.</p>

<p>Users should know what the API does, what an upgrade asks of them, and where to look when something fails. A small API, clear docs, and well-explained releases make that possible.</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://aallam.com/assets/images/generated/posts/2026-05-09-writing-libraries-is-writing-contracts.png" />
        <media:content medium="image" url="https://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">Java Memory Model</title>
      <link href="https://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://aallam.com/java-memory-model</id>
      
      
        <content type="html" xml:base="https://aallam.com/java-memory-model/"><![CDATA[<div class="text-center">
  <p><img src="https://aallam.com/assets/images/blog/cart-observing-wrong.png" alt="Java" width="50%" /></p>
</div>

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

<p>A <strong>data race</strong> occurs when two conflicting accesses to one variable lack a happens-before ordering. At least one access writes the variable. A program with a data race can observe values that surprise a reader who expects one shared execution order.</p>

<p>The <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html">Java 8 memory model</a> defines which values a read may see. It describes language guarantees, independent of a particular processor cache or JIT compiler.</p>

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

<p>Within one thread, execution must preserve the behavior that Java assigns to that thread. Across threads, a correctly synchronized program appears sequentially consistent. A racy program does not receive that guarantee.</p>

<p>For example, these ordinary fields have no ordering between a writer and reader:</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="kt">int</span> <span class="n">bar</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">write</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="n">bar</span> <span class="o">=</span> <span class="mi">1</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kt">int</span> <span class="nf">read</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">bar</span> <span class="o">==</span> <span class="mi">1</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="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>A reader can observe <code class="language-plaintext highlighter-rouge">bar == 1</code> without a guarantee that it sees <code class="language-plaintext highlighter-rouge">foo == 1</code>. The memory model permits this result because neither access establishes a happens-before edge. Do not interpret the example as a claim about a specific cache operation.</p>

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

<p>Most single variable reads and writes are atomic. Under Java 8, a non-<code class="language-plaintext highlighter-rouge">volatile</code> <code class="language-plaintext highlighter-rouge">long</code> or <code class="language-plaintext highlighter-rouge">double</code> access may be treated as two 32-bit accesses. A <code class="language-plaintext highlighter-rouge">volatile</code> access to either type is atomic.</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">value</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">writeLowBits</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">value</span> <span class="o">=</span> <span class="mh">0x00000000FFFFFFFF</span><span class="no">L</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kt">void</span> <span class="nf">writeHighBits</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">value</span> <span class="o">=</span> <span class="mh">0xFFFFFFFF00000000</span><span class="no">L</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>If writes tear, a racing read could combine the upper half from one write with the lower half from the other. Possible mixed values include <code class="language-plaintext highlighter-rouge">0x0000000000000000L</code> and <code class="language-plaintext highlighter-rouge">0xFFFFFFFFFFFFFFFFL</code>. A particular JVM need not produce either value. This example explains a permitted behavior, not a reliable experiment.</p>

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

<p>The model covers <strong>visibility</strong>, <strong>ordering</strong>, and <strong>atomicity</strong>. Visibility asks which write a read may observe. Ordering relates actions across threads. Atomicity asks whether one access can be observed in pieces.</p>

<p>A happens-before relation joins program order with synchronization rules. If a write happens-before a read of the same field, that ordering constrains which values the read can observe. Happens-before does not require an immediate hardware cache flush.</p>

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

<p>Program order connects earlier actions to later actions within one thread. Synchronization adds edges across threads, including volatile write-to-read, monitor unlock-to-lock, thread start, and successful thread join. Happens-before is transitive: if A precedes B and B precedes C, A precedes C.</p>

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

<p>A write to a <code class="language-plaintext highlighter-rouge">volatile</code> field happens-before each subsequent read of that field in synchronization order. Ordinary writes before the volatile write become visible to a reader after that read.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">PublishedAnswer</span> <span class="o">{</span>
    <span class="kt">int</span> <span class="n">answer</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="kt">void</span> <span class="nf">publish</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="kc">true</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kt">int</span> <span class="nf">read</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">if</span> <span class="o">(!</span><span class="n">ready</span><span class="o">)</span> <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="o">;</span>
        <span class="k">return</span> <span class="n">answer</span><span class="o">;</span> <span class="c1">// 42 if this read observed publish()</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>A reader can see <code class="language-plaintext highlighter-rouge">ready == false</code> before publication. If it reads the published <code class="language-plaintext highlighter-rouge">true</code>, it must also see the earlier <code class="language-plaintext highlighter-rouge">answer = 42</code>, assuming no other writes race with <code class="language-plaintext highlighter-rouge">answer</code>. <code class="language-plaintext highlighter-rouge">volatile</code> does not make compound operations such as <code class="language-plaintext highlighter-rouge">count++</code> atomic.</p>

<div class="text-center">
  <p><img src="https://aallam.com/assets/images/blog/volatile_sync.png" alt="Volatile Synchronization" /></p>
  <figcaption class="caption">The write to the volatile flag publishes earlier writes to a reader that observes the flag.</figcaption>
</div>

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

<p>A monitor unlock happens-before each later lock of the same monitor. Both methods below use the object’s monitor. Each method releases that monitor when it returns.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">MonitorAnswer</span> <span class="o">{</span>
    <span class="kd">private</span> <span class="kt">boolean</span> <span class="n">ready</span><span class="o">;</span>
    <span class="kd">private</span> <span class="kt">int</span> <span class="n">answer</span><span class="o">;</span>

    <span class="kd">synchronized</span> <span class="kt">void</span> <span class="nf">publish</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="kc">true</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="kd">synchronized</span> <span class="kt">int</span> <span class="nf">read</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">ready</span> <span class="o">?</span> <span class="n">answer</span> <span class="o">:</span> <span class="o">-</span><span class="mi">1</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>If <code class="language-plaintext highlighter-rouge">read()</code> acquires the monitor before <code class="language-plaintext highlighter-rouge">publish()</code>, it returns <code class="language-plaintext highlighter-rouge">-1</code>. If <code class="language-plaintext highlighter-rouge">publish()</code> completes first, <code class="language-plaintext highlighter-rouge">read()</code> returns <code class="language-plaintext highlighter-rouge">42</code>. The lock protects the check and the value together. A loop that holds this lock while waiting for <code class="language-plaintext highlighter-rouge">ready</code> would prevent <code class="language-plaintext highlighter-rouge">publish()</code> from acquiring it.</p>

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

<p>Actions before a call to <code class="language-plaintext highlighter-rouge">Thread.start()</code> happen-before actions in the started thread. Actions in a thread happen-before another thread successfully returns from <code class="language-plaintext highlighter-rouge">join()</code> on it.</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">value</span><span class="o">;</span>

    <span class="kt">void</span> <span class="nf">runExample</span><span class="o">()</span> <span class="kd">throws</span> <span class="nc">InterruptedException</span> <span class="o">{</span>
        <span class="n">value</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</span>
        <span class="nc">Thread</span> <span class="n">worker</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Thread</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
            <span class="k">if</span> <span class="o">(</span><span class="n">value</span> <span class="o">!=</span> <span class="mi">42</span><span class="o">)</span> <span class="k">throw</span> <span class="k">new</span> <span class="nc">AssertionError</span><span class="o">();</span>
            <span class="n">value</span> <span class="o">=</span> <span class="mi">43</span><span class="o">;</span>
        <span class="o">});</span>
        <span class="n">worker</span><span class="o">.</span><span class="na">start</span><span class="o">();</span>
        <span class="n">worker</span><span class="o">.</span><span class="na">join</span><span class="o">();</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">value</span> <span class="o">!=</span> <span class="mi">43</span><span class="o">)</span> <span class="k">throw</span> <span class="k">new</span> <span class="nc">AssertionError</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The start edge publishes <code class="language-plaintext highlighter-rouge">42</code> to the worker. The successful join edge publishes the worker’s <code class="language-plaintext highlighter-rouge">43</code> to the caller.</p>

<div class="text-center">
  <p><img src="https://aallam.com/assets/images/blog/thread_lifecycle.png" alt="Thread Life-cycle" /></p>
  <figcaption class="caption">Actions before start reach the worker. Worker actions reach a thread after successful join.</figcaption>
</div>

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

<p>A correctly constructed object has special guarantees for its <code class="language-plaintext highlighter-rouge">final</code> fields. Its reference may be shared without ordinary synchronization, but the object must not escape during construction.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Settings</span> <span class="o">{</span>
    <span class="kd">final</span> <span class="kt">int</span> <span class="n">limit</span><span class="o">;</span>

    <span class="nc">Settings</span><span class="o">(</span><span class="kt">int</span> <span class="n">limit</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">this</span><span class="o">.</span><span class="na">limit</span> <span class="o">=</span> <span class="n">limit</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="kd">class</span> <span class="nc">Holder</span> <span class="o">{</span>
    <span class="kd">static</span> <span class="nc">Settings</span> <span class="n">shared</span><span class="o">;</span>

    <span class="kd">static</span> <span class="kt">void</span> <span class="nf">publish</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">shared</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Settings</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>A thread that obtains the <code class="language-plaintext highlighter-rouge">Settings</code> reference sees <code class="language-plaintext highlighter-rouge">limit == 42</code>, provided the constructor did not let <code class="language-plaintext highlighter-rouge">this</code> escape. This guarantee does not ensure that another thread discovers the new <code class="language-plaintext highlighter-rouge">shared</code> reference. It also does not make later changes to other fields visible. Use synchronization or <code class="language-plaintext highlighter-rouge">volatile</code> when discovery or later updates matter.</p>

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

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

<p>Double-checked locking needs a <code class="language-plaintext highlighter-rouge">volatile</code> reference and a second check while holding the lock:</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">private</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">final</span> <span class="kt">int</span> <span class="n">value</span><span class="o">;</span>

    <span class="kd">private</span> <span class="nf">DoubleChecked</span><span class="o">()</span> <span class="o">{</span>
        <span class="n">value</span> <span class="o">=</span> <span class="mi">42</span><span class="o">;</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="nc">DoubleChecked</span> <span class="n">result</span> <span class="o">=</span> <span class="n">instance</span><span class="o">;</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">result</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="n">result</span> <span class="o">=</span> <span class="n">instance</span><span class="o">;</span>
                <span class="k">if</span> <span class="o">(</span><span class="n">result</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
                    <span class="n">result</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DoubleChecked</span><span class="o">();</span>
                    <span class="n">instance</span> <span class="o">=</span> <span class="n">result</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">result</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The volatile publication makes constructor writes visible to readers that obtain the instance. The inner check prevents two creators from publishing separate instances. Without <code class="language-plaintext highlighter-rouge">volatile</code>, the unsynchronized first read has no publication guarantee.</p>

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

<p>A <code class="language-plaintext highlighter-rouge">volatile</code> array field makes reads and writes of the <strong>array reference</strong> volatile. It does not make element accesses volatile.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">ArrayReference</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="o">{</span><span class="kc">false</span><span class="o">};</span>

    <span class="kt">void</span> <span class="nf">publish</span><span class="o">()</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="o">{</span><span class="kc">true</span><span class="o">};</span> <span class="c1">// volatile reference write</span>
    <span class="o">}</span>

    <span class="kt">boolean</span> <span class="nf">read</span><span class="o">()</span> <span class="o">{</span>
        <span class="k">return</span> <span class="n">ready</span><span class="o">[</span><span class="mi">0</span><span class="o">];</span> <span class="c1">// volatile reference read, then ordinary element read</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>A reader that observes the new reference also sees its initialized element. Mutating <code class="language-plaintext highlighter-rouge">ready[0]</code> later does not create another volatile edge. For coordinated element updates, use a suitable atomic array such as <code class="language-plaintext highlighter-rouge">AtomicIntegerArray</code>, or use a lock.</p>

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

<ul>
  <li><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html">Java 8 JLS, Chapter 17: Threads and Locks</a></li>
  <li><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5">Java 8 JLS, happens-before order</a></li>
  <li><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.5">Java 8 JLS, final field semantics</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://aallam.com/assets/images/blog/cart-observing-wrong.png" />
        <media:content medium="image" url="https://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://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://aallam.com/java-virtual-machine-architecture</id>
      
      
        <content type="html" xml:base="https://aallam.com/java-virtual-machine-architecture/"><![CDATA[<div class="text-center">
  <p><img src="https://aallam.com/assets/images/blog/JVM.png" alt="Java" width="50%" /></p>
</div>

<p>This article describes the Java 8 JVM specification and the Java 8 HotSpot implementation. Other JVMs can make different implementation choices.</p>

<p>Java source files become portable bytecode when <code class="language-plaintext highlighter-rouge">javac</code> compiles them. A JVM loads the resulting <code class="language-plaintext highlighter-rouge">.class</code> files and executes their instructions. HotSpot can interpret bytecode or compile frequently used code into native machine code.</p>

<p>The <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html">JVM specification</a> defines an abstract machine. It leaves memory layout, garbage collection, and native-code optimization to implementations.</p>

<div class="text-center">
  <p><img src="https://aallam.com/assets/images/blog/JVM_Architecture.png" alt="JVM Architecture" width="75%" /></p>
  <figcaption class="caption">Java 8 JVM architecture overview. The diagram illustrates an implementation. The specification does not require this layout.</figcaption>
</div>

<h2 id="1-class-loader-subsystem">1. Class Loader Subsystem</h2>

<p>A class must be loaded, linked, and initialized before certain uses. These stages are distinct. Loading can also happen before a class is first used.</p>

<h3 id="11-loading">1.1. Loading</h3>

<p>In Java 8 HotSpot, class loaders find class definitions and create their runtime representation:</p>

<ul>
  <li>The <strong>bootstrap loader</strong> loads core Java classes, commonly from <code class="language-plaintext highlighter-rouge">rt.jar</code> in a Java 8 installation.</li>
  <li>The <strong>extension loader</strong> searches extension directories after delegating to its parent.</li>
  <li>The <strong>application loader</strong> searches the application class path after delegating to its parent.</li>
</ul>

<p>You can also define a custom class loader. Parent delegation is the usual pattern, but custom loaders can choose different behavior.</p>

<div class="text-center">
  <p><img src="https://aallam.com/assets/images/blog/java_class_loaders.png" alt="Java Class Loaders" /></p>
  <figcaption class="caption">Typical Java 8 HotSpot class-loader hierarchy.</figcaption>
</div>

<h3 id="12-linking">1.2. Linking</h3>

<p><strong>Verification</strong> checks that a class file follows the format and bytecode rules. Invalid bytecode can cause a <code class="language-plaintext highlighter-rouge">VerifyError</code>.</p>

<p><strong>Preparation</strong> creates static fields with default values. It does not execute their Java initializers.</p>

<p><strong>Resolution</strong> turns symbolic references into runtime references. A JVM may resolve a reference when it first needs it, rather than resolving every reference during initial linking.</p>

<h3 id="13-initialization">1.3. Initialization</h3>

<p>Initialization runs the class or interface initialization method, named <code class="language-plaintext highlighter-rouge">&lt;clinit&gt;</code> in bytecode. The compiler combines static field initializers and <code class="language-plaintext highlighter-rouge">static</code> blocks into this method. For example, <code class="language-plaintext highlighter-rouge">static int count = 42;</code> assigns <code class="language-plaintext highlighter-rouge">42</code> during initialization, after preparation first assigns <code class="language-plaintext highlighter-rouge">0</code>.</p>

<p>Creating an instance, invoking a static method, or reading or writing a nonconstant static field can trigger class initialization. A class is initialized before its first instance is constructed. Instance field initializers and constructors run for each new object. <code class="language-plaintext highlighter-rouge">&lt;clinit&gt;</code> runs once per class initialization. Compile-time constant reads can avoid initialization.</p>

<p>The JVM coordinates initialization across threads. See the <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.5">initialization rules</a> for precise triggers and ordering.</p>

<h2 id="2-runtime-data-areas">2. Runtime Data Areas</h2>

<p>The specification defines shared and per-thread data areas. It does not prescribe their physical layout.</p>

<h3 id="21-method-area-shared">2.1 Method Area (Shared)</h3>

<p>The method area holds per-class structures, including the runtime constant pool, field and method data, and method code. All JVM threads share it.</p>

<p><strong>Metaspace</strong> is HotSpot’s Java 8 implementation choice for much class metadata. It uses native memory. Do not treat Metaspace as a second method area required by the specification. The exact placement of static field values is an implementation detail.</p>

<h3 id="22-heap-area-shared">2.2 Heap Area (Shared)</h3>

<p>The heap holds class instances and arrays. All JVM threads share it. Each instance has its own instance fields. A class has one set of static fields.</p>

<h3 id="23-stack-area-per-thread">2.3. Stack Area (Per thread)</h3>

<p>Each JVM thread has its own JVM stack. A method call creates a frame with local variables, an operand stack, and information needed for return and dynamic linking. The frame disappears when the call completes normally or abruptly.</p>

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

<p>A stack can have a fixed or dynamic size. Excessive call depth can cause <code class="language-plaintext highlighter-rouge">StackOverflowError</code>. A JVM can throw <code class="language-plaintext highlighter-rouge">OutOfMemoryError</code> if it cannot create or expand a stack.</p>

<h3 id="24-pc-registers--per-thread">2.4. PC Registers  (Per thread)</h3>

<p>Each JVM thread has a program-counter register. For a nonnative method, it identifies the current JVM instruction. Its value is undefined while the thread executes a native method.</p>

<h3 id="25-native-method-stack-per-thread">2.5. Native Method Stack (Per thread)</h3>

<p>An implementation can use native method stacks for native calls. The specification does not require one operating-system thread or one separate native stack for every Java thread. Java 8 HotSpot commonly maps Java threads to native threads.</p>

<h2 id="3-execution-engine">3. Execution Engine</h2>

<p>The JVM executes bytecode instructions using these runtime data areas. The specification defines instruction behavior, while HotSpot chooses how to run it.</p>

<h3 id="31-interpreter">3.1. Interpreter</h3>

<p>HotSpot can interpret bytecode as a method runs. Interpretation avoids an initial compilation cost, but repeated execution can benefit from compiled code.</p>

<h3 id="32-just-in-time-jit-compiler">3.2. Just-In-Time (JIT) Compiler</h3>

<p>HotSpot profiles running code and compiles selected methods or loops into native code. Compilation has a cost, so HotSpot makes adaptive decisions based on observed execution. Compiled code can later be replaced or deoptimized when assumptions change.</p>

<p>This is an implementation strategy, not a requirement that every JVM use a JIT compiler. Interpretation and compilation have different startup and steady-state costs. Neither makes Java inherently slow.</p>

<h3 id="33-garbage-collector">3.3. Garbage Collector</h3>

<p>A garbage collector traces references from roots, such as live stack references and static fields. It can reclaim an object when no root can reach it. Two objects that refer only to each other can both be reclaimed if no root reaches their cycle.</p>

<p>The JVM specification leaves the collection algorithm to the implementation. HotSpot’s collectors differ in pause times, throughput, and memory use.</p>

<h2 id="4-java-native-interface-jni">4. Java Native Interface (JNI)</h2>

<p>JNI lets Java code call native libraries and lets native code interact with the JVM. Native code can have platform-specific behavior and needs its own safety checks.</p>

<h2 id="5-native-method-libraries">5. Native Method Libraries</h2>

<p>Native libraries contain platform-specific functions, often written in C or C++. JNI is one way to call them from Java.</p>

<h2 id="6-jvm-threads">6. JVM Threads</h2>

<p>Application threads execute Java code. The <code class="language-plaintext highlighter-rouge">main</code> thread starts the program’s <code class="language-plaintext highlighter-rouge">main</code> method, but other application threads need not be created directly by it. A thread pool worker, for example, can create another thread.</p>

<p>Java 8 HotSpot also uses internal threads for work such as compilation and garbage collection. Its exact thread names and counts depend on configuration and collector. The JVM specification does not require the same internal threads in every implementation.</p>

<h2 id="7-conclusion">7. Conclusion</h2>

<p><code class="language-plaintext highlighter-rouge">javac</code> compiles source into bytecode. A Java 8 JVM loads and verifies that bytecode, manages runtime data, and executes instructions. HotSpot combines interpretation, JIT compilation, and garbage collection to balance startup, throughput, pauses, and memory use.</p>

<h2 id="8-useful-commands">8. Useful Commands</h2>

<ul>
  <li><code class="language-plaintext highlighter-rouge">javac</code>: compile Java source files.</li>
  <li><code class="language-plaintext highlighter-rouge">javap -c ClassName</code>: inspect bytecode instructions.</li>
  <li><code class="language-plaintext highlighter-rouge">jps</code>: list Java processes visible to the tool.</li>
  <li><code class="language-plaintext highlighter-rouge">jcmd</code>: list visible Java processes and send diagnostic commands.</li>
  <li><code class="language-plaintext highlighter-rouge">jcmd [PID] help</code>: list commands supported by that JVM.</li>
  <li><code class="language-plaintext highlighter-rouge">jcmd [PID] GC.heap_dump [PATH]</code>: write a heap dump.</li>
  <li><code class="language-plaintext highlighter-rouge">jcmd [PID] Thread.print</code>: print thread stacks.</li>
  <li><code class="language-plaintext highlighter-rouge">-XX:+PrintCompilation</code>: log HotSpot compilation activity.</li>
  <li><code class="language-plaintext highlighter-rouge">-XX:+PrintInlining</code>: log HotSpot inlining decisions when diagnostic options permit it.</li>
</ul>

<p>These commands and <code class="language-plaintext highlighter-rouge">-XX</code> options describe the Java 8 HotSpot toolchain. Availability can vary by JDK build.</p>

<h2 id="9-sources">9. Sources</h2>

<ul>
  <li><a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.5">Java 8 JVM specification: runtime data areas</a></li>
  <li><a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html">Java 8 JVM specification: loading, linking, and initialization</a></li>
  <li><a href="http://blog.jamesdbloom.com/JVMInternals.html">JVM Internals</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://aallam.com/assets/images/blog/JVM.png" />
        <media:content medium="image" url="https://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://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://aallam.com/reactivex:-rxjava</id>
      
      
        <content type="html" xml:base="https://aallam.com/reactivex-rxjava/"><![CDATA[<div class="text-center">
  <p><img src="https://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> I wrote this series for RxJava 2.x in 2019. RxJava 3.x changed some APIs. See the <a href="https://github.com/ReactiveX/RxJava/wiki/What's-different-in-3.0">RxJava 3.x migration guide</a> when using that version.</p>
</blockquote>

<p>I enjoyed Thomas Nield’s <a href="https://www.amazon.com/Learning-RxJava-Thomas-Nield/dp/1787120422">Learning RxJava</a>. These are my notes on RxJava 2.</p>

<h2 id="why-rxjava">Why RxJava?</h2>
<ul>
  <li>Combine events from several sources into one stream.</li>
  <li>Move work to a scheduler and deliver results to a chosen thread.</li>
  <li>Transform values, stop subscriptions, and recover from errors with operators.</li>
</ul>

<h2 id="quickstart">Quickstart</h2>
<p>In RxJava 2, an <code class="language-plaintext highlighter-rouge">Observable&lt;T&gt;</code> emits values of type <code class="language-plaintext highlighter-rouge">T</code> to a subscriber. Operators can transform those values before the subscriber receives them.</p>

<p>This <code class="language-plaintext highlighter-rouge">Observable&lt;String&gt;</code> contains three strings:</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>This method creates an observable but does not subscribe. Add a subscriber to print its values:</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>The subscriber prints each string followed by a space. In the output above, ␠ marks the final space.</p>

<p>Use <code class="language-plaintext highlighter-rouge">map()</code> to transform each string before printing it:</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 uses the same spacing:</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>An <code class="language-plaintext highlighter-rouge">Observable</code> emits items to subscribers. Java streams and Kotlin sequences yield items when consumers request them. RxJava also supplies operators for asynchronous events and scheduler control.</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://aallam.com/rxjava-observable-and-observer">Observable &amp; Observer</a> - Core concepts and Observable factories</li>
  <li><a href="https://aallam.com/rxjava-hot-vs-cold-observable">Hot vs Cold Observable</a> - Understanding observable behavior patterns</li>
  <li><a href="https://aallam.com/rxjava-observable-factories">Observable Factories</a> - Additional factory methods (range, interval, timer, etc.)</li>
  <li><a href="https://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://aallam.com/rxjava-supressing-operators">Suppressing</a> - filter, take, skip, distinct</li>
  <li><strong>Transformation</strong>: <a href="https://aallam.com/rxjava-transforming-operators">Transforming</a> - map, flatMap, concatMap, switchMap</li>
  <li><strong>Aggregation</strong>: <a href="https://aallam.com/rxjava-reducing-operators">Reducing</a> - count, reduce, all, any</li>
  <li><strong>Collection</strong>: <a href="https://aallam.com/rxjava-collection-operators">Collection</a> - toList, toMap, collect</li>
  <li><strong>Error Handling</strong>: <a href="https://aallam.com/rxjava-recovery-operators">Recovery</a> - onErrorReturn, onErrorResumeNext</li>
  <li><strong>Side Effects</strong>: <a href="https://aallam.com/rxjava-action-operators">Action</a> - doOnNext, doOnComplete, doOnError</li>
</ul>

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

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

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

<h3 id="customization">Customization</h3>
<ul>
  <li><a href="https://aallam.com/rxjava-transformers">Transformers</a> - Reusable operator chains</li>
  <li><a href="https://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>These Kotlin examples use RxJava directly. <a href="https://github.com/ReactiveX/RxKotlin">RxKotlin</a> offers Kotlin-specific extensions.</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://aallam.com/assets/images/blog/reactivex.png" />
        <media:content medium="image" url="https://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://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://aallam.com/java-8-interface-methods-for-android</id>
      
      
        <content type="html" xml:base="https://aallam.com/java-8-interface-methods-for-android/"><![CDATA[<div class="text-center">
  <p><img src="https://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 post follows four steps to show how D8 works:</p>
<ol>
  <li>Write Java source (<code class="language-plaintext highlighter-rouge">.java</code>).</li>
  <li>Compile it to bytecode (<code class="language-plaintext highlighter-rouge">.class</code>).</li>
  <li>Compile the bytecode to a Dalvik executable (<code class="language-plaintext highlighter-rouge">.dex</code>).</li>
  <li>Inspect the generated files.</li>
</ol>

<p>These steps show how D8 desugars Java 8 features such as lambdas and APIs.</p>

<p>I use the same steps to examine <code class="language-plaintext highlighter-rouge">default</code> and <code class="language-plaintext highlighter-rouge">static</code> methods in Java 8 interfaces. I recommend reading Jake Wharton’s post first.</p>

<h2 id="compile-java-8-code">Compile Java 8 Code</h2>
<p>Consider this 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>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>Running it prints:</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 compile the bytecode to dex with 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>Use <code class="language-plaintext highlighter-rouge">dexdump</code> to inspect the interface methods:</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>First, find this 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>D8 generated <code class="language-plaintext highlighter-rouge">Java8$Logger-CC</code>, as the <code class="language-plaintext highlighter-rouge">SYNTHETIC</code> flag shows. It extends <code class="language-plaintext highlighter-rouge">Object</code>, implements no interfaces, and has no fields.</p>

<p>Now inspect the 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>This static method takes a <code class="language-plaintext highlighter-rouge">Logger</code> followed by the default method’s arguments. Its body 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>The bytecode performs the same work as the interface’s default method. Equivalent Java code is:</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>D8 moved the default method’s body to a static method in the generated <code class="language-plaintext highlighter-rouge">Java8$Logger-CC</code> class.</p>

<h2 id="static-method">Static Method</h2>
<p>The generated <code class="language-plaintext highlighter-rouge">Java8$Logger-CC</code> class also contains the interface’s static <code class="language-plaintext highlighter-rouge">systemOut</code> method:</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><code class="language-plaintext highlighter-rouge">systemOut</code> takes no arguments and returns a <code class="language-plaintext highlighter-rouge">Logger</code>. Its body 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>This code implements <code class="language-plaintext highlighter-rouge">Logger.systemOut()</code>. The generated lambda class represents the <code class="language-plaintext highlighter-rouge">System.out::println</code> method reference.</p>

<p>Equivalent Java code is:</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>This Java code models the transformed class. I changed some 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://aallam.com/assets/images/blog/android_desugar.png" />
        <media:content medium="image" url="https://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://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://aallam.com/hello-world</id>
      
      
        <content type="html" xml:base="https://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>I wanted to set up my own website and blog for a long time. I made a few shy attempts, but this one is here to stay! Welcome to my blog and this unavoidable “Hello, world!” post! :D</p>

<p>I built this blog with <a href="http://jekyllbootstrap.com/">Jekyll</a> and the <a href="https://github.com/sergiokopplin/indigo">Indigo theme</a>. The source code is on <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://aallam.com/assets/images/generated/posts/2016-04-06-hello-world.png" />
        <media:content medium="image" url="https://aallam.com/assets/images/generated/posts/2016-04-06-hello-world.png" xmlns:media="http://search.yahoo.com/mrss/" />
      
    </entry>
  
</feed>
