Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Garbage Collection
Search
Stefan Kanev
November 03, 2013
Programming
0
200
Garbage Collection
OpenFest 2013 talk about garbage collection
Stefan Kanev
November 03, 2013
Tweet
Share
More Decks by Stefan Kanev
See All by Stefan Kanev
Въведение в (Machine|Deep) Learning
skanev
0
73
GraphQL
skanev
0
360
Automated Testing: Getting it Right
skanev
1
48
From Novice to Expert
skanev
0
420
Inbetween Code and Profession
skanev
0
360
Clojure & ClojureScript
skanev
2
100
Extreme Programming
skanev
0
590
За смъртта на TDD
skanev
0
490
Python 0 2014
skanev
1
1.6k
Other Decks in Programming
See All in Programming
組織に自動テストを書く文化を根付かせる戦略(2024秋版) / Building Automated Test Culture 2024 Autumn Edition
twada
PRO
10
4.3k
『ドメイン駆動設計をはじめよう』のモデリングアプローチ
masuda220
PRO
4
150
推し活としてのrails new/oshikatsu_ha_iizo
sakahukamaki
3
1.1k
Vue SFCのtemplateでTypeScriptの型を活用しよう
tsukkee
3
1.4k
僕がつくった48個のWebサービス達
yusukebe
17
16k
Kotlinの好きなところ
kobaken0029
0
220
Going Staff - Keynote edition
pragtob
0
430
#pixiv小説画像メーカー はこうしてできた / The Making of the pixiv Novel Image Maker
roiban
0
220
リリース8年目のサービスの1800個のERBファイルをViewComponentに移行した方法とその結果
katty0324
2
2.8k
【Kaigi on Rails 2024】YOUTRUST スポンサーLT
krpk1900
0
210
Go言語でターミナルフレンドリーなAIコマンド、afaを作った/fukuokago20_afa
monochromegane
2
140
JaSST 24 九州:ワークショップ(は除く)実践!マインドマップを活用したソフトウェアテスト+活用事例
satohiroyuki
0
170
Featured
See All Featured
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
328
21k
Dealing with People You Can't Stand - Big Design 2015
cassininazir
364
22k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
3
360
Making Projects Easy
brettharned
115
5.9k
Principles of Awesome APIs and How to Build Them.
keavy
126
17k
Why You Should Never Use an ORM
jnunemaker
PRO
53
9k
Adopting Sorbet at Scale
ufuk
73
9k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
9
670
How To Stay Up To Date on Web Technology
chriscoyier
788
250k
Agile that works and the tools we love
rasmusluckow
327
21k
Testing 201, or: Great Expectations
jmmastey
38
7k
Large-scale JavaScript Application Architecture
addyosmani
510
110k
Transcript
Garbage Collection Стефан Кънев http://skanev.com/ @skanev OpenFest 3 ноември 2013
София
Здравейте, аз съм Стефан
DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS
twitter @skanev github skanev blog http://skanev.com/
Всеки път
03.11.2013
I ❤︎ LEGACY
@current_year = 2011 ‑︎ @current_year = 2012
None
2.0 & 2.1
I ❤︎ LEGACY
?
Garbage Collection
None
None
“The undecidability of liveness is a corollary to the halting
problem” — Garbage Collection, Jones et al
None
Stop-and-Copy 1 hour coding 6 hours debugging
Garbage Collection
None
BG PUBLIC ENEMY №1
-а/-ът
None
Ще деплойнем в пръдъкшън след като билда мине на кънтиниъс
интегрейшъна. DISCLAIMER
събирачи на смет свободни списъци пържоли корени
<rant>
Пълният член смуче!
None
ЦСКА vs. Левски
ЦСКА vs. Балкан Ботевград
Долу пълния член!
#ътставка
</rant>
i.Garbage Collection ii.Algorithms iii.Classifications iv.Languages v.Ruby 2.0 & Ruby 2.1
i.Garbage Collection ii.Algorithms iii.Classifications iv.Languages v.Ruby 2.0 & Ruby 2.1
Автоматично освобождаване на неизползваната памет, без баене от страна на
програмиста
това включва и Reference counting
Не целя: kernel developer-и с Garbage Collector web developer-и с
malloc()
Целя: kernel developer-и с Garbage Collector web developer-и с malloc()
Целя: Да добиете някаква представа за collector-ите и особеностите им
Common misconceptions
None
✔! алокацията е по-бърза от malloc()
✘ паузи по минута са възможни
heap памет, където обекти се алокират в произволен ред mutator
програмата (променя паметта) roots стека и регистрите live set паметта, достъпна от корените pointer “стрелка” от един обект към друг cells/objects парчета управлявана памет garbage недостижимата памет
i = 0 while i < N: i += 1
doSomething(i)
Динамично алокиране
None
<=>
O(nlgn)
cnlgn
CPU cache virtual memory*
различни приложения, различни pattern-и на работа
сложен инженерен проблем
i.Garbage Collection ii.Algorithms iii.Classifications iv.Languages v.Ruby 2.0 & Ruby 2.1
REFERENCE COUNTING MARK & SWEEP MARK & COMPACT COPY
Reference Counting
1. Всеки обект има брояч 2. Всеки указател увеличава брояча
3. Триенето на указател намалява 4. free() когато брояча е нула Outline
roots 1 1 REFERENCE COUNTING
roots 1 2 REFERENCE COUNTING
roots 1 1 REFERENCE COUNTING
roots 1 1 1 REFERENCE COUNTING
roots 1 0 1 REFERENCE COUNTING
roots 0 1 REFERENCE COUNTING
roots 1 REFERENCE COUNTING
просто & лесно
None
None
None
roots 1 1 REFERENCE COUNTING
roots 2 2 REFERENCE COUNTING
roots 1 2 REFERENCE COUNTING
roots 1 1 Memory Leak REFERENCE COUNTING
None
weak-refs разни алгоритми
чисто решение няма трябва tracing
None
roots 1 1 1 1 1 1 1 1 1
детерминизъм vs. паузи при големи обекти
✔; Проста имплементация ✔; Детерминистичност ✘ Инкрементации/декрементации ✘ Допълнителна памет
✘ Паузи при големи обекти* ✘ Не освобождава цикли ✔; Повече по-късно
Reference Counting има много варианти
<aside>
x = [] y = [] id(x) == id(y) =>
False id([]) == id([]) => True
a = [] a = id(a) b = [] b
= id(b) a == b
#lolpython
Mark & Sweep
малко интро
header header header heaps
header off-heap storage ✘
Free list Heap Heap MARK/SWEEP
1. Започваме от root-овете 2. Рекурсивно маркираме всичко, до което
може да стигнем 3. Трием немаркираното Outline
roots MARK/SWEEP
roots roots Garbage MARK/SWEEP
Heap MARK/SWEEP
Heap Fragmentation MARK/SWEEP
✔; Събира цикли ✔; По-икономичен (памет и процесор) ✘ Пауза
за обхождане и събиране* ✘ Повече cache misses ✘ Недетерминистичен ✘ Нужда от свободна памет ✘ Линеен на спрямо heap-а
Mark & Compact
1. Маркираме всичко 2. Местим обекти в дупките 3. Обновяваме
указателите Outline
MARK/COMPACT
MARK/COMPACT
STALE POINTERS MARK/COMPACT Active Memory Forwarding Adresses
✔; Евтина алокация ✔; Дефрагментира паметта ✘ Линейно на heap-а
✘ Копирането е бавно ✘ Няма свободни pointer-и (мести)
Copy
1. Разделяме heap-а на две 2. Алокираме в едната половина
3. Копираме достижимото в другата Outline
From space To space COPY
From space To space COPY
From space To space COPY
✔; Евтина алокация ✔; Дефрагментира паметта ✔; Линейно на живите
обекти ✘ 50% място разхищение ✘ Трябва да мести обекти
i.Garbage Collection ii.Algorithms iii.Classifications iv.Languages v.Ruby 2.0 & Ruby 2.1
STOP-THE-WORLD vs. INCREMENTAL vs. PARALLEL vs. CONCURRENT
STOP-THE-WORLD collector mutator
INCREMENTAL sweep mutator mark ✔! Разпределени кратки паузи ✘ Overhead
при алокация
PARALLEL collector mutator
CONCURRENT collector mutator ✔! Не спира света ✘ Overhead за
синхронизация
MOSTLY CONCURRENT collector mutator ✘ Мутатора и колектора се гонят
CONSERVATIVE vs. PRECISE
Трябва помощ от компилатора
None
Weak generational hypothesis: Most objects die young
1. Разделяме heap-а на млади и стари 2. Събираме основно
младите (minor) 3. От време на време събираме старата генерация (major cycle) Outline
Old Generation New Generation roots
Old Generation New Generation roots roots
Old Generation New Generation roots roots
Old Generation New Generation roots roots BUG ☢
WRITE BARRIER
old ˠ young
roots Old Generation New Generation remembered set
i.Garbage Collection ii.Algorithms iii.Classifications iv.Languages v.Ruby 2.0 & Ruby 2.1
Reference counting No cycle detection ;(
Reference counting Full cycle detection
Reference counting Almost full cycle detection
__del__ finalizers
gc.garbage
trololothon
Mark and sweep Incremental, conservative (...)
Java!
None
4
1 SerialGC Stop-the-world copy for young generation Stop-the-world mark/compact for
old generation
2 ParallelGC Stop-the-world copy for young generation Stop-the-world mark/compact for
old generation
3 ConcMarkSweepGC Stop-the-world copy for young generation Mostly concurrent, non-compacting
mark- sweep for older generation Fallback to stop-the-world compacting full collection
4 G1GC Stop-the-world copy for young generation Mostly concurrent marking
old generation Stop-the-world, mostly incremental compacting for old generation Fallback to stop-the-world compaction
HotSpot JRockit IBM J9 Azul Zing
None
None
C C++
Boehm-Demers Collector http://www.hpl.hp.com/personal/Hans_Boehm/gc/
malloc ! GC_MALLOC realloc ! GC_REALLOC
scan the stack find all pointers mark/sweep
detect memory leaks
None
i.Garbage Collection ii.Algorithms iii.Classifications iv.Languages v.Ruby 2.0 & Ruby 2.1
2.0 & 2.1
CoW friendly ‐︎ copy-on-write
None
None
None
RGenGC
None
RARRAY_PTR(obj)
#define RARRAY_PTR(a) \ ((RBASIC(a)->flags & RARRAY_EMBED_FLAG) ? \ RARRAY(a)->as.ary :
\ RARRAY(a)->as.heap.ptr)
break lots of C extensions vs. non-generational GC
Shady Sunny
Shady objects, - go into the remembered set when shaded
- do not get promoted in the old generation
#define RARRAY_PTR(a) \ ((VALUE *) \ RARRAY_CONST_PTR(RGENGC_WB_PROTECTED_ARRAY ?\ OBJ_WB_UNPROTECT((VALUE)a) :
\ ((VALUE)a)))
incrementally update the C extensions
incrementally update the virtual machine
I ❤︎ LEGACY
Books!
None
DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS
DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS DEVELOPERS
None