Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Garbage Collection for Humans

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest. →

Garbage Collection for Humans

Garbage Collection (GC) history, origins and evolution with a focus on JVM.

Avatar for Dogan Ersoz

Dogan Ersoz

November 13, 2019

Other Decks in Programming

Transcript

  1. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Who am I? • Electrical & Electronics Engineer (2002) • MSc in Cryptography • 15 years in Defense Industry R&D • Since 2018 in Semiconductor Industry • Polyglot developer • 10+ years JVM • Father of two boys
  2. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    https://octoverse.github.com/ GitHub Ranking 2018 2019 Garbage Collection? JavaScript 1 1 YES Python 3 2 YES(Mixed) Java 2 3 YES PHP 4 4 YES(Mixed) C# 6 5 YES C++ 5 6 NO TypeScript 7 7 YES Shell 9 8 NO C 8 9 NO Ruby 10 10 YES Why do you care?
  3. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    • Obvious: Memory errors • Example: OutOfMemoryError in JVM • Slower application over time • Memory leaks • Growing memory consumption • Wrong configurations
  4. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Brain Waste Disposal System http://sitn.hms.harvard.edu/flash/2018/clearing-junk-healthy-lifestyle-choices-boost-brain-waste-disposal/ Pro Tip: Sleep is important!
  5. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    How to clean ‘computer garbage’ • Manual • Aka manual memory management (C[malloc, free], C++[new, delete]) • Automatic • Automatic reference counting (Swift, C++[std::shared_ptr]) • Garbage Collection (Java, C#)
  6. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    In C and C++ freeing allocated memory is thought to be so important that it should be handled explicitly by the programmer using free/delete. the Garbage Collector” Charles Griffiths
  7. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Source 5balloons.info Written in online IDE https://repl.it
  8. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    In C# and Java freeing allocated memory is thought to be so important that it should be handled automatically using the Garbage Collector the Garbage Collector” Charles Griffiths
  9. John McCarthy Father of Artificial Intelligence Creator of LISP Creator

    of first Garbage Collector 1971 Turing Award Recipient https://catonmat.net/what-would-john-mccarthy-say-if-he-saw-you-programming
  10. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Why do we need Garbage Collection (GC)? • Moving responsibility of labor work from humans to machine • Automating memory allocation and deallocation • Preventing human errors • Minimizing possible memory leaks • Increasing developer productivity
  11. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    https://octoverse.github.com/ GitHub Ranking 2018 2019 GC JavaScript 1 1 YES Python 3 2 YES(Mixed) Java 2 3 YES PHP 4 4 YES(Mixed) C# 6 5 YES C++ 5 6 NO TypeScript 7 7 YES Shell 9 8 NO C 8 9 NO Ruby 10 10 YES
  12. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    If GC is convenient, why not all use it? • Historical reasons • Performance (memory overhead, CPU load) • Predictability
  13. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Is there a productive and performant option? • Automatic reference counting (?) • When the reference count drops to zero the object is definitely unreachable and can be recycled
  14. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Swift Cyclic Reference ARC https://www.raywenderlich.com/966538-arc-and-memory-management-in-swift class User { let name: String private(set) var phones: [Phone] = [] func add(phone: Phone) { phones.append(phone) phone.owner = self } } class Phone { let model: String var owner: User? } func runScenario() { let user = User(name: "John") let iPhone = Phone(model: "iPhone Xs") user.add(phone: iPhone); } !!! Retain cycle problem 2 objects keep a reference to each other
  15. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Swift ARC Reference Types https://www.raywenderlich.com/966538-arc-and-memory-management-in-swift
  16. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Garbage Collection Marking the cycles for cleaning https://plumbr.io/handbook/what-is-garbage-collection
  17. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Automatic Reference Counting • (+) Performant / deterministic compared to GC • (+) Can clean up entire object graphs • (+) Happens in the background no memory management effort needed • (+) Developer friendly, less prone to human errors • (-) Cannot cope with cycles • (-) Still some instructions from user required [Objective-C, Swift] [Java, C#] GC • (-) Can block application flow while doing GC • (-) Developer has no control over the scheduling, not deterministic • (-) Requires additional resources (memory, CPU) ARC vs GC
  18. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Productivity vs Performance • Manual memory managed systems are more performant • If everything is perfect and no human error • Trade off • General trend is towards productivity • JavaScript is # 1
  19. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Requirements of a GC • Functional Requirements • Automatic deallocation of allocated memory • Non Functional Requirements • Throughput • Latency • Memory layout constraints
  20. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Functional - Reachability GC Roots • Local variables • Active Java Threads • Static variables • JNI references https://plumbr.io/handbook/what-is-garbage-collection
  21. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Functional - Mark & Sweep • Proposed by Lisp inventor John McCarthy in 1960 • Each object has a ‘Mark Bit’ • Initially ‘0’ • Set to ‘1’ if reachable https://i.stack.imgur.com/W5pX6.gif
  22. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Non Functional - Throughput & Latency https://www.slideshare.net/waterfox1/an-introduction-to-jvm-internals-and-garbage-collection-in-java
  23. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Non Functional - Memory Layout https://nahuellofeudo.com/the-memory-hole/
  24. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Evaluating a GC • Pause time vs productive time • Pause frequency • Pause distribution • Allocation performance • Concurrency • Scaling • CPU usage • Memory footprint
  25. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Unused JVM Other Apps System Apps Kernel Host OS Memory Available Memory
  26. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    http://gustycooper.github.io/gustycooper.github.io/mydoc_5_stack_heap/ Stack and Heap
  27. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Stack • Used only by one thread of execution • Reclaimed when thread exits • Holds local primitive variables and references • LIFO access, easy to manage • java.lang.StackOverFlowError Stack vs Heap Heap • Used by the whole application, global memory • Reclaimed when GC kicks in or app exits • Holds actual object allocations • No enforced pattern, complex • java.lang.OutOfMemoryError
  28. Weak Generational Hypothesis • Most of the objects become unused

    quickly • The ones that do not usually survive for a (very) long time https://apprize.info/javascript/nutshell/7.html
  29. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Generations Young & Old • Young Generation • Cheap to collect [Minor GC] • Old Generation • Long lived objects in Young Generation are ‘promoted’ to old generation • Typically larger than Young Generation • Expensive to collect [Major GC] Eden S1 S2 Old Young Generation Minor GC Major GC
  30. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Promotion Rate & Premature Promotion https://plumbr.io/blog/garbage-collection/what-is-promotion-rate • The faster objects promoted to old, the faster it gets full • Which means young is not big enough for new allocations • Once old is full enough -> Major Collection is triggered • Hence ‘Premature Promotion’ • Solution: Increase the size of young generation
  31. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Promotion Failure https://plumbr.io/blog/garbage-collection/what-is-promotion-rate • If old is full during a Minor GC? • To promote young objects, a minor GC is followed by a Full GC • Hence, ‘Promotion Failure’ • Solution: Increase the size of old generation
  32. GC Events in JVM Type Target Trigger Impact Minor GC

    Young generation Eden getting full No effect on latency Major GC Old generation Minor GC fails Can have latency effect Full GC Whole heap + MetaSpace Minor or Major GC fail Can have latency effect
  33. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Serial GC (-XX:+UseSerialGC) • Stop the world & Serial • All GC work in a single thread • Pause times can be long • Grow more or less linearly with the heap size and amount of live data • Simplest & lowest memory footprint • Single processor, small data sets https://dzone.com/articles/choosing-the-right-gc
  34. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Parallel GC (-XX:+UseParallelGC) • STW & Parallel • Increased throughput • Default GC in JDK till Java 9 • Multithreaded old & young collectors • Memory tended to be 1GB – 2GB • Pause times increase with increased heap sizes • Does not support memory shrinking • Even after a Full GC, other processes will not be able to use available space • Not good for multi-tenant environments https://dzone.com/articles/choosing-the-right-gc
  35. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Concurrent Mark Sweep GC (-XX:+UseConcMarkSweepGC) • STW & Parallel Young Collection • Mostly Concurrent Old Collection • Good for lower worst-case pause times than Serial or Parallel GC • Reduced pause times • Sacrifices throughput • Tuning is hard concurrent work should be completed before out of memory • Requires 10-20% more heap space compared to Parallel GC • Compaction is not concurrent • Unpredictable DEPRECATED in Java 9 https://dzone.com/articles/choosing-the-right-gc
  36. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Traditional JVM GCs have some problems … • Necessity to scan whole OLD Generation • Mark, Sweep, Compact … • Huge heap → Huge latency • YOUNG and OLD are separate consecutive chunks of memory • Need to decide at JVM startup which one is which • Not flexible enough Eden S1 S2 Old Meta Young Generation
  37. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    A New Kind of Garbage Collector Eden S1 S2 Old https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/G1GettingStarted/images/slide9.pngI
  38. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    G1 GC (-XX:+UseG1GC) • STW & Parallel Young Collection • Concurrent mark reduces pauses significantly • Pauses are independent of heap size • Just set a pause time goal and let it work • Starts with the ‘dirtiest’ region first – Hence G1 • Has String Deduplication! • Compaction is still not concurrent https://dzone.com/articles/choosing-the-right-gc
  39. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Concurrency in Garbage Collection “With concurrent mark everything gets complicated: the application runs and actively mutates the object graph during the mark.” Alexey Shipilev
  40. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Concurrent Marking https://shipilev.net/talks/jugbb-Sep2019-shenandoah.pdf
  41. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    https://shipilev.net/talks/jugbb-Sep2019-shenandoah.pdf Concurrent evacuation
  42. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Shenandoah https://shipilev.net/talks/jugbb-Sep2019-shenandoah.pdf
  43. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    https://shipilev.net/talks/jugbb-Sep2019-shenandoah.pdf
  44. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    https://shipilev.net/talks/jugbb-Sep2019-shenandoah.pdf
  45. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: Choose the right GC • Need throughput => Choose Parallel GC • Need responsive app => Choose G1 or Shenandoah • Need multitenancy => Choose G1 or Shenandoah • Large heap: large live data sets ⇒ need concurrent GC • Slow hardware: memory is slow ⇒ need concurrent GC
  46. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: Use Immutable Objects “Object whose fields cannot be modified(*) after the creation” - Fields should be created before the object itself - The class is always younger than its fields - When young collection, GC can skip scanning immutable objects in older generations. They cannot reference any younger objects. Eden S1 S2 Old https://blog.overops.com/5-tips-for-reducing-your-java-garbage-collection-overhead/
  47. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: If size is known use it with collections
  48. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: Limit the scope • If defined in scope & Out of scope -> eligible for garbage collection • Can be for, while, switch kind of statement scope • Can be method scope • Can be class scope • Chose smallest scope possible
  49. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: Avoid unnecessary object creation in loops
  50. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: Use Specialized Primitive Collections • int is 4 bytes • Integer is 16 bytes • 12 Object header + 4 int https://blog.overops.com/5-tips-for-reducing-your-java-garbage-collection-overhead/
  51. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: Use static fields judiciously • Static fields are GC Roots! • Always reachable • Never eligible for garbage collection • One source for potential memory leaks in Java
  52. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: Log GC Activity • -XX:+PrintGCDetails • -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps • -Xloggc:<PathToLogFile>
  53. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: Heap Dump on Error • -XX:+HeapDumpOnOutOfMemoryError • -XX:HeapDumpPath=<PathToHeapDump>
  54. Buildstuff | Lithuania | 2019 @dersoz Garbage Collection for Humans

    Tip: Practical commands for JVM • Print all the default flags • > java -XX:+PrintFlagsFinal -version • Print current flags • > java -XX:+PrintCommandLineFlags -version • Enable String deduplication on G1 • > java -XX:+UseG1GC -XX:+UseStringDeduplication