Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 104 ยท Quality, Performance and Security

Dalvik, ART, DEX, Desugaring and Multidex

How Kotlin code becomes an Android app: javac and kotlinc, D8 and R8, DEX files, ART's AOT, JIT and profile-guided compilation, desugaring, multidex and APK vs AAB.

When you press Run, a lot happens between your Kotlin file and a pixel on the screen. Most days you can ignore it. But when a build fails with "Cannot fit requested classes in a single dex file", when an app starts slowly right after install, or when you wonder why a Java 17 feature works on an Android 8 phone, you need a picture of the machinery. This lesson gives you that picture: what a DEX file is, how the Android Runtime (ART) runs it, which tools produce it and why app bundles exist.

Nothing here runs on a phone from this site, so the TryIts are plain Kotlin stand-ins. They model the ideas (the compile stages, the method limit, the install-time size) with simple data, and each section says which parts are real and which are simplified.

From source code to a running app

Android phones do not run Java bytecode directly. The build turns your source into a different format, DEX (Dalvik Executable), a compact bytecode designed for small memory and storage. The pipeline looks like this:

flowchart LR
    A["Kotlin / Java source"] --> B["kotlinc / javac"]
    B --> C[".class files (JVM bytecode)"]
    C --> D["R8 (release) or D8 (debug)"]
    D --> E["classes.dex"]
    E --> F["APK / AAB"]
    F --> G["ART on the device"]

The stages between your source and a running app.

  1. kotlinc and javac compile your Kotlin and Java files into ordinary JVM .class files. At this point the code is the same kind of bytecode a desktop JVM runs.
  2. D8 is the dexer: it converts .class files, including those from your libraries, into .dex files. It also desugars newer language features (more below). In debug builds D8 is the tool that runs.
  3. R8 replaces D8 in release builds when minification is on. It does the dexing too, but first shrinks (removes unused code), optimizes and obfuscates, as covered in Performance and Profiling.
  4. The Android Gradle Plugin packages the DEX files, resources and the manifest into an APK or an AAB, and you sign it, see Signing and Release Builds.
Kotlin The build pipeline as data (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The 0.18 factor is invented to show the effect; real shrinking results depend on your app and your keep rules.

Dalvik, ART and the run-time story

The first Android versions ran DEX in Dalvik, a virtual machine that interpreted bytecode and, from Android 2.2, added a just-in-time (JIT) compiler. It was small and fast to start, but it did a lot of work at every launch.

ART (Android Runtime) replaced Dalvik as the default in Android 5.0 and is the only runtime today. Its strategy changed over time, and the history explains behavior you can still observe:

Android What ART does
5.0 to 6.0 Ahead-of-time (AOT): compile the whole app to native code at install. Fast to run, but slow installs and big files.
7.0 and later Hybrid: interpret and JIT-compile at first, record which code is hot in a profile, and compile only that part in the background while the device idles and charges (profile-guided optimization).
9 and later Cloud profiles from Google Play can arrive with the install; your own baseline profile can ship inside the app.
12 and later The ART runtime itself can be updated through Google Play system updates (the ART Mainline module).

This is the reason an app can feel slower on first launch after install: the code starts interpreted, and the optimized version only appears after use. A baseline profile (see Performance and Profiling) gives ART the list of hot methods up front, so it can compile them at install time. The compile mode of a package is inspectable on a device with adb shell dumpsys package <name> (look for "Dexopt state") and changeable with adb shell cmd package compile.

The word "Dalvik" survives in places: the file format is still called Dalvik Executable, tools print dalvik.system classes and logs say "dalvikvm" on old devices. But the thing that runs your app on any modern phone is ART.

Desugaring: new language features on old devices

Your code may use language features or Java library APIs that an old Android version does not have. Desugaring rewrites them at build time into forms that old runtimes understand. D8 and R8 do the work in two parts:

  • Language desugaring covers constructs such as lambdas, method references, default and static interface methods, try-with-resources and, in recent AGP versions, many newer Java syntax features. This is on by default and needs no setup.
  • Library desugaring (opt-in) backports parts of the Java library, such as java.time, to devices below the API level where they were added. You enable it with isCoreLibraryDesugaringEnabled = true in compileOptions and add the desugar_jdk_libs dependency.
Kotlin
// read-only example: needs Android
android {
    compileOptions {
        isCoreLibraryDesugaringEnabled = true
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }
}
dependencies {
    coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")
}

Library desugaring adds some code and a little startup cost, so enable it only when you support old API levels and truly use those APIs. With a high minSdk it is unnecessary. Kotlin itself does most of its own work: coroutines, data classes and lambdas are compiled by kotlinc into plain bytecode, and its standard library is just another dependency.

DEX files and the method limit

A single DEX file can reference at most 65,536 methods (2^16), because method indices are 16-bit. That counts every method your app references, including those from libraries. It is easier to reach than you would think: a handful of large libraries add tens of thousands.

Since Android 5.0 (API 21), ART supports multiple DEX files natively, so an app with classes.dex, classes2.dex and so on just works, and Gradle splits them for you. This is multidex. Today's minSdk is far above 21, so you almost never configure anything; the old multiDexEnabled line and androidx.multidex library mattered only for Android 4.4 and below, where a hand-written class loader had to stitch the files together and slowed startup.

Big DEX counts still have costs. More files means more work at class loading and installation, which is another reason to shrink with R8. For the main (first) DEX file there is an additional trick: code needed at startup should live in it, and the build can be told which classes via a keep file (multiDexKeepFile) if you must support legacy devices.

The next stand-in packs method counts into DEX files the way the build does, so you can see when a second file appears and how shrinking changes things.

Kotlin Packing methods into DEX files (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The numbers are made up but the algorithm is the real idea: the build fills a file until the limit and then starts another. After R8, everything fits in one DEX file, which also helps startup.

APK versus AAB: what reaches the device

An APK (Android Package) is the file a device installs: DEX files, compiled resources, native libraries and the manifest, in a ZIP. If you publish a single APK it has to carry resources for every screen density, every language and every CPU architecture, because it does not know which device will install it.

An AAB (Android App Bundle) is a publishing format. You upload one .aab to Google Play, and Play generates optimized APKs for each device: split APKs containing only the right density resources, language and ABI (arm64-v8a, x86_64, ...). Users download less, and you do not have to maintain several flavors. Since August 2021 Google Play requires AABs for new apps. Bundles also enable Play Feature Delivery (modules downloaded on demand) and Play Asset Delivery for games.

You cannot install an .aab directly. For local testing, bundletool builds APKs from it, and Android Studio does this when you run a bundle. For outlets outside Google Play (other stores, direct download) you still build a universal APK. The final download is a fraction of the universal APK size, as the stand-in below shows with typical component sizes.

Kotlin Universal APK versus a split install (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Checklist: what to do with this knowledge

  • Keep R8 on for release builds; it is the biggest lever on DEX size, startup and install size.
  • Ship a baseline profile, so ART compiles the important code at install instead of after several runs.
  • Do not configure multidex unless you support Android 4.4 or below.
  • Enable core library desugaring only when you need java.time and friends on old API levels.
  • Publish an AAB to Google Play, and keep the mapping file from each release to decode crash traces.
  • If a build reports "Cannot fit requested classes in a single dex file" on an old minSdk, shrink first and enable multidex second.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which tool turns .class files into DEX files in a release build with minification on?

    R8 shrinks, optimizes, obfuscates and dexes in release builds. D8 does only the dexing and desugaring and is used when minification is off.
  2. 2. Why can an app feel slow right after installation, and what helps?

    Since Android 7 ART starts with interpretation and JIT and compiles hot code later from a profile. A baseline profile supplies that list ahead of time.
  3. 3. What is the source of the 65,536 method limit in one DEX file?

    DEX method references are indexed with 16 bits. Multidex, supported natively since Android 5.0, simply uses several DEX files.
  4. 4. What is true about an AAB?

    You upload the bundle, and Play delivers only the density, language and ABI parts a device needs, which keeps downloads smaller.
  5. 5. When do you need library desugaring?

    Language features are desugared by default. Library desugaring is an opt-in backport of parts of the Java library for old devices.

Summary

  • Source is compiled to .class files by kotlinc and javac, then dexed by D8 (debug) or R8 (release) into .dex files, and packaged into an APK or AAB.
  • ART replaced Dalvik in Android 5.0. Modern ART interprets and JIT-compiles first, records a profile and compiles the hot code later; baseline profiles shortcut that.
  • D8 and R8 desugar new language features; library desugaring is opt-in for APIs like java.time on old devices.
  • A DEX file holds at most 65,536 method references; multidex is built in since API 21 and rarely needs setup today.
  • An AAB is what you upload to Google Play; Play delivers split APKs sized for each device.
  • R8, baseline profiles and an AAB are the three practical wins from understanding the runtime.

Next: Signing and Release Builds