SlideShare a Scribd company logo
Java Garbage Collection
AgendaIntroduction to GCIntroduction to GC AlgorithmsFinalize() in JavaReference type in Java
PurposeKnow how GC worksAvoid traps when works with GCEnhance program performance
AgendaIntroduction to GCIntroduction to GC AlgorithmsFinalize() in JavaReference type in Java
Introduction to GCGarbage CollectionUsed to release non-used memoriesJava specification doesn’t define detail of GC, each company can implement its own GCDifferent JVM has different GC algorithmSun – SolarisIBM – AIX…
Introduction to GCGC is a overhead, system has to stop current execution to execute GCcause short stop and may influence user experienceandroid team make it as short as possiblewe can do nothing to improve GC but improve our program
Stack & Heap memoryInstance variables and Objects lie on HeapLocal variables and methods lie on the StackEach running thread has its StackC++ has local objects (object in stack)All Java objects live in Heap
Stack & Heap memorypublic static void main() {int a;    People Rae = new People();    People Ear = new People();Rae.father = Ear; }
Stack & Heap memoryStackHeapPeopleEarRaePeoplea
Introduction to GCGC happens in Heap memory only
Stack & Heap memory
Stack & Heap memory
AgendaIntroduction to GCIntroduction to GC AlgorithmsFinalize() in JavaReference type in Java
Introduction to GC AlgorithmsDifferent JVM has different GC implementationsReference countingMark and SweepStop and CopyAdaptive…
Reference countingIf a object is referenced, the counter is increased by 1If reference to a object is removed, then the counter is decreased by 1GC will collect these object whose counter is 0
Reference counting - drawbackEach object should maintain a counterCan’t identify circular conditionStackHeapPeople(2)A(1)EarB(1)C(1)RaePeople(1)a
Mark and SweepThree phasesMark phaseSweep phaseCompact phase
Reachable ObjectRoot : the beginning of all referencereference from main()reference from static method()…if a object can be visited by a serious of reference from Root, it is called reachable, otherwise it is unreachableunreachable objects will be collected by GC
Garbage detection is ordinarily accomplished by defining a set of roots and determining reachability from the roots.An object is reachable if there is some path of references from the roots by which the executing program can access the object. The roots are always accessible to the program. Any objects that are reachable from the roots are considered live. Objects that are not reachable are considered garbage, because they can no longer affect the future course of program execution.
Mark phaseThere are two method to mark reachable objectsTracingReference counting
TracingFrom Roots, search all reachable objects and mark themavoid circular reference StackHeapPeopleAEarBCRaePeoplea
Sweep phaseAfter mark phase, these which not be referenced are not markedGC will release their memory
Compact phaseAfter several GCs, Heap may contain fragmentsNeed to be rearrangedTwo algorithmsCompactingCopying…
Compactingmove objects in Heap from one end to another end
CopyingCopy objects from one Heap to another HeapHeap AHeap B
Mark and SweepAvoid circular referenceHave to manage memory fragments
Stop and CopyCopy live object to another Heap and leave deadsHeap AHeap B
Stop and CopyNeed not to manage memory fragmentsDouble memory space needed
AdaptiveGC has more than one strategy to deal with garbage collectionGC can change strategy during garbage collection depending on heap status
final() method in ObjectIt is GC that execute final in every object
each thread of execution has its own stack.
Two basic approaches to distinguishing live objects from garbage are reference counting and tracing.
Reference counting garbage collectors distinguish live objects from garbage objects by keeping a count for each object on the heap. The count keeps track of the number of references to that object. Tracing garbage collectors, on the other hand, actually trace out the graph of references starting with the root nodes. Objects that are encountered during the trace are marked in some way. After the trace is complete, unmarked objects are known to be unreachable and can be garbage collected.
A disadvantage of reference counting is that it does not detect cycles.
Some Java objects have finalizers, others do not. Objects with finalizers that are left unmarked after the sweep phase must be finalized before they are freed. Unmarked objects without finalizers may be freed immediately unless referred to by an unmarked finalizable object. All objects referred to by a finalizable object must remain on the heap until after the object has been finalized.
Compacting collectorsTwo strategies commonly used by mark and sweep collectors are compacting and copying.heap fragmentation
AgendaIntroduction to GCIntroduction to GC AlgorithmsFinalize() in JavaReference type in Java
finalize()Called before the object's memory is being reclaimed by the VM.The default implementation of the method is empty, which is also expected by the VM, but subclasses can override finalize() as required.Uncaught exceptions which are thrown during the execution of this method cause it to terminate immediately but are otherwise ignored. Note that the VM does guarantee that finalize() is called at most once for any object, but it doesn't guarantee when (if at all) finalize() will be called.
finalize()If one object override its finalize(), this object is called finalizableIf a object doesn’t override its finalize(), when GC collect it, its memory is freed directlyIf a object is finalizable, when GC collect it, this object will be send into a queue, and its finalize() will then be executedAfter finalize() been successfully executed, then it will be release in next GC
finalize()If a object is referenced by an finalizable object, it will be released after the finalizable object is released

More Related Content

PPSX
Introduction to Java
PPTX
Garbage collection
ODP
Python Presentation
PDF
4 pillars of OOPS CONCEPT
PPTX
Object oriented programming
PDF
Java conditional statements
PDF
Constructors and Destructors
PPT
Java basic introduction
Introduction to Java
Garbage collection
Python Presentation
4 pillars of OOPS CONCEPT
Object oriented programming
Java conditional statements
Constructors and Destructors
Java basic introduction

What's hot (20)

PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PPT
Exception Handling in JAVA
PPTX
Hibernate ppt
ODP
Garbage collection
PPTX
Method overloading
PDF
C++ OOPS Concept
PPTX
Multithreading in java
PDF
Java Garbage Collection - How it works
PPTX
Java abstract class & abstract methods
PPTX
Basic Data Types in C++
PPT
friend function(c++)
PDF
Methods in Java
PPTX
Applets in java
PPS
Wrapper class
PDF
Oops concepts || Object Oriented Programming Concepts in Java
PPT
The Evolution of Java
PPT
android activity
PPT
Shared preferences
PPTX
Android activity lifecycle
PPTX
File handling
Basic Concepts of OOPs (Object Oriented Programming in Java)
Exception Handling in JAVA
Hibernate ppt
Garbage collection
Method overloading
C++ OOPS Concept
Multithreading in java
Java Garbage Collection - How it works
Java abstract class & abstract methods
Basic Data Types in C++
friend function(c++)
Methods in Java
Applets in java
Wrapper class
Oops concepts || Object Oriented Programming Concepts in Java
The Evolution of Java
android activity
Shared preferences
Android activity lifecycle
File handling
Ad

Viewers also liked (20)

PPT
Mark and sweep algorithm(garbage collector)
PDF
Understanding Java Garbage Collection
PDF
Let's talk about Garbage Collection
PPT
Basic Garbage Collection Techniques
PDF
How long can you afford to Stop The World?
PDF
JVM及其调优
PDF
淺談 Java GC 原理、調教和 新發展
PDF
Introduction of Java GC Tuning and Java Java Mission Control
PDF
Understanding Garbage Collection
PDF
Java GC Tuning
PPT
enums
ODP
Gc algorithms
PPT
16 Java Regex
PPTX
Jvm基础调优实践(v1.0)
PDF
About garbage collection
PDF
[BGOUG] Java GC - Friend or Foe
PDF
Java GC - Pause tuning
PDF
Java gc
PPTX
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
PPT
Java Garbage Collection(GC)- Study
Mark and sweep algorithm(garbage collector)
Understanding Java Garbage Collection
Let's talk about Garbage Collection
Basic Garbage Collection Techniques
How long can you afford to Stop The World?
JVM及其调优
淺談 Java GC 原理、調教和 新發展
Introduction of Java GC Tuning and Java Java Mission Control
Understanding Garbage Collection
Java GC Tuning
enums
Gc algorithms
16 Java Regex
Jvm基础调优实践(v1.0)
About garbage collection
[BGOUG] Java GC - Friend or Foe
Java GC - Pause tuning
Java gc
Вячеслав Блинов «Java Garbage Collection: A Performance Impact»
Java Garbage Collection(GC)- Study
Ad

Similar to Java GC (20)

PDF
Why using finalizers is a bad idea
PDF
Garbage collection 介紹
DOC
Memory management
PDF
Managing Memory in Swift (Yes, that's a thing)
PDF
C# basics
PPTX
Garbagecollectionhgfhgfhgfhgfgkfkjfkjkjfkjfjhfg.pptx
ODP
Garbage Collection in Hotspot JVM
PDF
Garbage Collection in Java.pdf
PDF
Java Garbage Collector and The Memory Model
PPTX
.NET UY Meetup 7 - CLR Memory by Fabian Alves
PDF
RxJava@DAUG
PDF
RxJava@Android
PPT
Gc in android
PDF
My Rmi F
PDF
Memory Leaks in Android Applications
PDF
The things we don't see – stories of Software, Scala and Akka
PPT
Garbage Collection In Micorosoft
PDF
Java reference objects basic
PPTX
Exploring .NET memory management (iSense)
PDF
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Why using finalizers is a bad idea
Garbage collection 介紹
Memory management
Managing Memory in Swift (Yes, that's a thing)
C# basics
Garbagecollectionhgfhgfhgfhgfgkfkjfkjkjfkjfjhfg.pptx
Garbage Collection in Hotspot JVM
Garbage Collection in Java.pdf
Java Garbage Collector and The Memory Model
.NET UY Meetup 7 - CLR Memory by Fabian Alves
RxJava@DAUG
RxJava@Android
Gc in android
My Rmi F
Memory Leaks in Android Applications
The things we don't see – stories of Software, Scala and Akka
Garbage Collection In Micorosoft
Java reference objects basic
Exploring .NET memory management (iSense)
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera

Recently uploaded (20)

PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
01-Introduction-to-Information-Management.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Structure & Organelles in detailed.
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
01-Introduction-to-Information-Management.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
STATICS OF THE RIGID BODIES Hibbelers.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Anesthesia in Laparoscopic Surgery in India
Cell Structure & Organelles in detailed.
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial disease of the cardiovascular and lymphatic systems
Abdominal Access Techniques with Prof. Dr. R K Mishra
TR - Agricultural Crops Production NC III.pdf
Final Presentation General Medicine 03-08-2024.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Week 4 Term 3 Study Techniques revisited.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Cell Types and Its function , kingdom of life
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...

Java GC

  • 2. AgendaIntroduction to GCIntroduction to GC AlgorithmsFinalize() in JavaReference type in Java
  • 3. PurposeKnow how GC worksAvoid traps when works with GCEnhance program performance
  • 4. AgendaIntroduction to GCIntroduction to GC AlgorithmsFinalize() in JavaReference type in Java
  • 5. Introduction to GCGarbage CollectionUsed to release non-used memoriesJava specification doesn’t define detail of GC, each company can implement its own GCDifferent JVM has different GC algorithmSun – SolarisIBM – AIX…
  • 6. Introduction to GCGC is a overhead, system has to stop current execution to execute GCcause short stop and may influence user experienceandroid team make it as short as possiblewe can do nothing to improve GC but improve our program
  • 7. Stack & Heap memoryInstance variables and Objects lie on HeapLocal variables and methods lie on the StackEach running thread has its StackC++ has local objects (object in stack)All Java objects live in Heap
  • 8. Stack & Heap memorypublic static void main() {int a; People Rae = new People(); People Ear = new People();Rae.father = Ear; }
  • 9. Stack & Heap memoryStackHeapPeopleEarRaePeoplea
  • 10. Introduction to GCGC happens in Heap memory only
  • 11. Stack & Heap memory
  • 12. Stack & Heap memory
  • 13. AgendaIntroduction to GCIntroduction to GC AlgorithmsFinalize() in JavaReference type in Java
  • 14. Introduction to GC AlgorithmsDifferent JVM has different GC implementationsReference countingMark and SweepStop and CopyAdaptive…
  • 15. Reference countingIf a object is referenced, the counter is increased by 1If reference to a object is removed, then the counter is decreased by 1GC will collect these object whose counter is 0
  • 16. Reference counting - drawbackEach object should maintain a counterCan’t identify circular conditionStackHeapPeople(2)A(1)EarB(1)C(1)RaePeople(1)a
  • 17. Mark and SweepThree phasesMark phaseSweep phaseCompact phase
  • 18. Reachable ObjectRoot : the beginning of all referencereference from main()reference from static method()…if a object can be visited by a serious of reference from Root, it is called reachable, otherwise it is unreachableunreachable objects will be collected by GC
  • 19. Garbage detection is ordinarily accomplished by defining a set of roots and determining reachability from the roots.An object is reachable if there is some path of references from the roots by which the executing program can access the object. The roots are always accessible to the program. Any objects that are reachable from the roots are considered live. Objects that are not reachable are considered garbage, because they can no longer affect the future course of program execution.
  • 20. Mark phaseThere are two method to mark reachable objectsTracingReference counting
  • 21. TracingFrom Roots, search all reachable objects and mark themavoid circular reference StackHeapPeopleAEarBCRaePeoplea
  • 22. Sweep phaseAfter mark phase, these which not be referenced are not markedGC will release their memory
  • 23. Compact phaseAfter several GCs, Heap may contain fragmentsNeed to be rearrangedTwo algorithmsCompactingCopying…
  • 24. Compactingmove objects in Heap from one end to another end
  • 25. CopyingCopy objects from one Heap to another HeapHeap AHeap B
  • 26. Mark and SweepAvoid circular referenceHave to manage memory fragments
  • 27. Stop and CopyCopy live object to another Heap and leave deadsHeap AHeap B
  • 28. Stop and CopyNeed not to manage memory fragmentsDouble memory space needed
  • 29. AdaptiveGC has more than one strategy to deal with garbage collectionGC can change strategy during garbage collection depending on heap status
  • 30. final() method in ObjectIt is GC that execute final in every object
  • 31. each thread of execution has its own stack.
  • 32. Two basic approaches to distinguishing live objects from garbage are reference counting and tracing.
  • 33. Reference counting garbage collectors distinguish live objects from garbage objects by keeping a count for each object on the heap. The count keeps track of the number of references to that object. Tracing garbage collectors, on the other hand, actually trace out the graph of references starting with the root nodes. Objects that are encountered during the trace are marked in some way. After the trace is complete, unmarked objects are known to be unreachable and can be garbage collected.
  • 34. A disadvantage of reference counting is that it does not detect cycles.
  • 35. Some Java objects have finalizers, others do not. Objects with finalizers that are left unmarked after the sweep phase must be finalized before they are freed. Unmarked objects without finalizers may be freed immediately unless referred to by an unmarked finalizable object. All objects referred to by a finalizable object must remain on the heap until after the object has been finalized.
  • 36. Compacting collectorsTwo strategies commonly used by mark and sweep collectors are compacting and copying.heap fragmentation
  • 37. AgendaIntroduction to GCIntroduction to GC AlgorithmsFinalize() in JavaReference type in Java
  • 38. finalize()Called before the object's memory is being reclaimed by the VM.The default implementation of the method is empty, which is also expected by the VM, but subclasses can override finalize() as required.Uncaught exceptions which are thrown during the execution of this method cause it to terminate immediately but are otherwise ignored. Note that the VM does guarantee that finalize() is called at most once for any object, but it doesn't guarantee when (if at all) finalize() will be called.
  • 39. finalize()If one object override its finalize(), this object is called finalizableIf a object doesn’t override its finalize(), when GC collect it, its memory is freed directlyIf a object is finalizable, when GC collect it, this object will be send into a queue, and its finalize() will then be executedAfter finalize() been successfully executed, then it will be release in next GC
  • 40. finalize()If a object is referenced by an finalizable object, it will be released after the finalizable object is released
  • 41. Finalizable - DrawbackAll finalizable need to be executed by an independent thread, but the priority of this is not highMay keep too much unused object in Heap If its finalize() does not execute corrected (return Exception), then this object will never be releasedAll objects it refer to will never be released
  • 42. What can I do to improve GCfinalize() is supposed to be used to release memory only (ex. native code)Set obj = null whenever this object is no longer usedSome Java objects provide reusable objects, use them instead of creating new one (ex. Thread pool)Do not override finalize() if really not necessary
  • 43. AgendaIntroduction to GCIntroduction to GC AlgorithmsFinalize() in JavaReference type in Java
  • 44. Reference Type in JavaReference type associates with GCThere are four kind of references in JavaStrong referenceSoft referenceWeak referencePhantom reference
  • 45. Reference Type in JavaStrongly reachable: An object that can be accessed by a strong reference.Softly reachable: An object that is not strongly reachable and can be accessed through a soft reference.Weakly reachable: An object that is not strongly or softly reachable and can be accessed through a weak reference.Phantomly reachable: An object that is not strongly, softly, or weakly reachable, has been finalized, and can be accessed through a phantom reference.
  • 46. Strong ReferenceObject obj = new Object();GC can not free Strong reachable object until there are no more reference to this object
  • 47. Soft ReferenceNot a solid referenceWhen Memory is not enough, GC can release Soft reachable objectsGood implement to data cache
  • 48. Weak ReferenceWeaker than Soft referenceEvery time when GC starts, weak reachable objects are collectedDisposable objects
  • 49. Weak ReferenceOnce the garbage collector decides that an object obj is is weakly-reachable, the following happens: A set ref of references is determined. ref contains the following elements: All weak references pointing to obj. All weak references pointing to objects from which obj is either strongly or softly reachable. All references in ref are atomically cleared. All objects formerly being referenced by ref become eligible for finalization. At some future point, all references in ref will be enqueued with their corresponding reference queues, if any.
  • 50. Phantom ReferenceWeakest referenceWork with ReferenceQueue classThe PhantomReference class is useful only to track the impending collection of the referring object.When the garbage collector determines an object is phantomly reachable, the PhantomReference object is placed on its ReferenceQueue.The PhantomReference object referred to has been finalized and is ready to be collected.
  • 51. Phantom ReferencePhantom references are useful for implementing cleanup operations that are necessary before an object gets garbage-collected. They are sometimes more flexible than the finalize() method.