Android from the foundation · Puzzle 11 of 16
Sharing memory without sharing mistakes
If every app were a full copy of Zygote, memory would run out fast. The kernel makes the copies share, and copies only what changes.
The problem
In puzzle 10, every app process started as a copy of Zygote. But Zygote holds a lot: ART and the whole framework. Twenty apps, twenty full copies? The phone would run out of memory. And yet each app must be able to change its own data without changing anyone else's.
See it
The kernel hands out memory in small blocks of the same size: pages. Zygote's ART and framework fill many of them.
Step 1 of 4After a fork, the new processes don't get their own copies: they share Zygote's pages instead of copying them. Predict: what if your app changes one?
Step 2 of 4Then, and only then, the kernel copies that one page for your app. The others keep the original: copy-on-write.
Step 3 of 4Most pages are never changed, so they stay shared: twenty apps cost little more than one framework.
Step 4 of 4
The building block
The kernel hands out memory in small fixed-size blocks called pages.
When a process forks, the kernel doesn't copy the pages. The original (Zygote) and the new process share them. Only when one of them writes to a page, that is, changes it, does the kernel make a private copy of that one page for the writer: that's copy-on-write. Everything nobody changes stays shared, so twenty apps cost little more than one framework.
That doesn't break puzzle 0's rule. The shared pages hold only what came from Zygote, the same ART and framework every app has: never one app's own data. Nobody writes to a shared page itself: a write goes to a private copy. So no process can see or change another's own data.
The analogy
Every new house uses the show house's furniture. Repaint a chair, and only then do you get your own copy of that chair. The other houses keep the original.
Check yourself
Sources
What you now know
Memory comes in pages. After a fork, parent and child share every page; a page is copied only when one of them writes to it: copy-on-write.
Answer every question above correctly to unlock the next puzzle.