什么是Android的Zygote写时复制堆?核心疑问解析
Great question—let’s unpack this clearly, because Zygote’s copy-on-write (CoW) behavior is deeply tied to Linux process mechanics, not the Java-level CoW you might be familiar with (like CopyOnWriteArrayList).
First, a quick recap of Zygote’s role
Zygote starts up early in the Android boot process, preloading all core Android framework classes, system resources, and common libraries into its own heap. When the system needs to launch a new app process, it forks the Zygote process instead of starting from scratch.
How Linux fork + CoW works here
Linux’s fork() system call creates a child process that initially shares all memory pages with the parent (Zygote)—it doesn’t copy the entire heap immediately. This is where the "copy-on-write" part kicks in:
- As long as neither the parent (Zygote) nor any child app process modifies a shared memory page, everyone uses the same physical memory.
- Only when a process tries to write to a shared page does the kernel create a private copy of that specific page for the writing process. All other processes continue using the original unmodified page.
What gets copied in the Zygote heap?
It’s not entire classes or regions—it’s individual 4KB memory pages (the smallest unit of memory management in Linux). Here are common scenarios that trigger a copy:
- An app modifies a static field in a framework class (e.g., changing a value in a system class that Zygote preloaded).
- An app dynamically loads a class that alters shared memory pages tied to framework resources.
- Rare cases where Zygote itself modifies a page (though Zygote is mostly read-only after preloading).
Key difference from Java-level CoW
Java’s CoW collections (like CopyOnWriteArrayList) are application-layer abstractions: when you modify the collection, the entire list is copied in user space. Zygote’s CoW is a kernel-level optimization for inter-process memory sharing, designed to save physical memory by avoiding redundant copies of unmodified system resources across dozens of app processes.
To sum up
Zygote heap’s copy-on-write is directly tied to the Linux fork() process. It copies only the specific memory pages that are being written to, not entire classes or heap regions, and it’s nothing like the CoW logic used in Java collections. The goal is to let all app processes share the preloaded framework resources until they need to make their own modifications.
内容的提问来源于stack exchange,提问作者Nick Cardoso

