SlideShare a Scribd company logo
1 of 17
Preventing memory leaks 
Ali Muzaffar
Common causes of memory leaks 
 Which Context to use? 
 Application Context 
 Activity Context 
 Problem with references outside of context 
 Why should Handlers be static? 
 Should inner classes be static? 
 Recycle bitmaps
Common causes of memory leaks 
 Which Context to use? 
 Application Context 
 Activity Context 
 Problem with references outside of context 
 Why should Handlers be static? 
 Should inner classes be static? 
 Leaking Threads 
 Also, Recycling Bitmaps (not covered here).
Which Context? 
Which is better? 
1. new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); 
2. new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, list); 
3. new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, list); 
1. new TextView(this); 
2. new TextView(getApplicationContext()); 
3. new TextView(getBaseContext());
Which is better? 
1. new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); 
2. new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, list); 
3. new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, list); 
1. new TextView(this); 
2. new TextView(getApplicationContext()); 
3. new TextView(getBaseContext());
Good rule of thumb 
 Always use Application Context. 
 Use Activity where necessary. Meaning the object will be 
collected with the Activity or method specifically requests 
it. 
 Never use getBaseContext().
Problem with references outside context 
 Why using the right context is important? 
 Threads & Garbage Collection 
 How do we fix this?
Usually not a problem 
@Override 
protected void onCreate(Bundle state) { 
super.onCreate(state); 
TextView label = new TextView(this); 
label.setText("Leaks are bad"); 
setContentView(label); 
} 
//Code by Romain Guy
Now it’s a problem 
private static Drawable sBackground; 
@Override 
protected void onCreate(Bundle state) { 
super.onCreate(state); 
TextView label = new TextView(this); 
label.setText("Leaks are bad"); 
if (sBackground == null) { 
sBackground = getDrawable(R.drawable.large_bitmap); 
} 
label.setBackgroundDrawable(sBackground); 
setContentView(label); 
} 
//Code by Romain Guy 
Drawables hold references to 
the Activity. 
TextView holds a strong 
reference to the Activity. The 
Drawable is not garbage 
collected, as a result, neither 
is the TextView or the 
Activity.
The problem with non-static inner 
classes 
 Why do I get this error?
Consider this piece of code
So whats the issue with non-static inner 
classes 
 When an Android application first starts, the framework creates a Looper object 
for the application's main thread. A Looper implements a simple message queue, 
processing Message objects in a loop one after another. All major application 
framework events (such as Activity lifecycle method calls, button clicks, etc.) 
are contained inside Message objects, which are added to the Looper's message 
queue and are processed one-by-one. The main thread's Looper exists throughout 
the application's lifecycle. 
 When a Handler is instantiated on the main thread, it is associated with the 
Looper's message queue. Messages posted to the message queue will hold a 
reference to the Handler so that the framework can call 
Handler#handleMessage(Message) when the Looper eventually processes the 
message. 
 In Java, non-static inner and anonymous classes hold an implicit reference to 
their outer class. Static inner classes, on the other hand, do not.
So what’s the issue with Threads? 
 Threads can be leaked along with/without 
memory. 
 Why? 
 Threads in Java are GC roots; that is, the Dalvik Virtual 
Machine (DVM) keeps hard references to all active 
threads in the runtime system, and as a result, threads 
that are left running will never be eligible for garbage 
collection.
Crouton 
 Why do we have to call 
Crouton.cancelAllCroutons() 
?
Crouton 
 Why do we have to call 
Crouton.cancelAllCroutons() 
?
What can we do? 
 Do not reference anything outside of it’s scope. 
 Try to not have long living objects. 
 Don’t assume java will clean up your threads. 
 Implement cancellation policies for background threads. 
 WeakReference
Egg-xample!

More Related Content

What's hot

Class method object
Class method objectClass method object
Class method objectMinal Maniar
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Velocity 2015 building self healing systems (slide share version)
Velocity 2015 building self healing systems (slide share version)Velocity 2015 building self healing systems (slide share version)
Velocity 2015 building self healing systems (slide share version)SOASTA
 
Heap and stack space in java
Heap and stack space in javaHeap and stack space in java
Heap and stack space in javaTalha Ocakçı
 
JProfiler8 @ OVIRT
JProfiler8 @ OVIRTJProfiler8 @ OVIRT
JProfiler8 @ OVIRTLiran Zelkha
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassCODE WHITE GmbH
 
Java 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureJava 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureSander Mak (@Sander_Mak)
 
Exception handling
Exception handlingException handling
Exception handlingMinal Maniar
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Christian Schneider
 
Internals of AsyncTask
Internals of AsyncTask Internals of AsyncTask
Internals of AsyncTask BlrDroid
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Incident Resolution as Code
Incident Resolution as CodeIncident Resolution as Code
Incident Resolution as CodeJulien Pivotto
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksMaulik Shah
 

What's hot (20)

Class method object
Class method objectClass method object
Class method object
 
Android concurrency
Android concurrencyAndroid concurrency
Android concurrency
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Velocity 2015 building self healing systems (slide share version)
Velocity 2015 building self healing systems (slide share version)Velocity 2015 building self healing systems (slide share version)
Velocity 2015 building self healing systems (slide share version)
 
Heap and stack space in java
Heap and stack space in javaHeap and stack space in java
Heap and stack space in java
 
Java memory model
Java memory modelJava memory model
Java memory model
 
JProfiler8 @ OVIRT
JProfiler8 @ OVIRTJProfiler8 @ OVIRT
JProfiler8 @ OVIRT
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
Java 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the futureJava 7: Fork/Join, Invokedynamic and the future
Java 7: Fork/Join, Invokedynamic and the future
 
Exception handling
Exception handlingException handling
Exception handling
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
 
Internals of AsyncTask
Internals of AsyncTask Internals of AsyncTask
Internals of AsyncTask
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Incident Resolution as Code
Incident Resolution as CodeIncident Resolution as Code
Incident Resolution as Code
 
Memory Leak In java
Memory Leak In javaMemory Leak In java
Memory Leak In java
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 

Viewers also liked

Identifying memory leaks in Android applications
Identifying memory leaks in Android applicationsIdentifying memory leaks in Android applications
Identifying memory leaks in Android applicationsZachary Blair
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android ApplicationsLokesh Ponnada
 
lightning talk : Android memory leak
lightning talk :  Android memory leaklightning talk :  Android memory leak
lightning talk : Android memory leakDeivison Sporteman
 
Memory management for_android_apps
Memory management for_android_appsMemory management for_android_apps
Memory management for_android_appsBin Shao
 
[Vietnam Mobile Day 2013] - Memory management for android applications
[Vietnam Mobile Day 2013] - Memory management for android applications[Vietnam Mobile Day 2013] - Memory management for android applications
[Vietnam Mobile Day 2013] - Memory management for android applicationsAiTi Education
 
Detecting Memory Leaks in Android App
Detecting Memory Leaks in Android AppDetecting Memory Leaks in Android App
Detecting Memory Leaks in Android AppDinesh Prajapati
 
Detect all memory leaks with LeakCanary!
 Detect all memory leaks with LeakCanary! Detect all memory leaks with LeakCanary!
Detect all memory leaks with LeakCanary!Pierre-Yves Ricau
 
LCA13: Memory Hotplug on Android
LCA13: Memory Hotplug on AndroidLCA13: Memory Hotplug on Android
LCA13: Memory Hotplug on AndroidLinaro
 
Memory management in Android
Memory management in AndroidMemory management in Android
Memory management in AndroidKeyhan Asghari
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in AndoidMonkop Inc
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationCITSimon
 
Memory leak analyse
Memory leak analyseMemory leak analyse
Memory leak analyseBernd Zuther
 
Facebook interview questions
Facebook interview questionsFacebook interview questions
Facebook interview questionsSumit Arora
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaXamarin
 
RetroFit by Square - GDG Dallas 06/09/16
RetroFit by Square - GDG Dallas 06/09/16RetroFit by Square - GDG Dallas 06/09/16
RetroFit by Square - GDG Dallas 06/09/16Stacy Devino
 
GKAC 2015 Apr. - Xamarin forms, mvvm and testing
GKAC 2015 Apr. - Xamarin forms, mvvm and testingGKAC 2015 Apr. - Xamarin forms, mvvm and testing
GKAC 2015 Apr. - Xamarin forms, mvvm and testingGDG Korea
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchasAlec Tucker
 
GKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android LooperGKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android LooperGDG Korea
 

Viewers also liked (20)

Identifying memory leaks in Android applications
Identifying memory leaks in Android applicationsIdentifying memory leaks in Android applications
Identifying memory leaks in Android applications
 
Memory leak
Memory leakMemory leak
Memory leak
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android Applications
 
lightning talk : Android memory leak
lightning talk :  Android memory leaklightning talk :  Android memory leak
lightning talk : Android memory leak
 
Memory management for_android_apps
Memory management for_android_appsMemory management for_android_apps
Memory management for_android_apps
 
[Vietnam Mobile Day 2013] - Memory management for android applications
[Vietnam Mobile Day 2013] - Memory management for android applications[Vietnam Mobile Day 2013] - Memory management for android applications
[Vietnam Mobile Day 2013] - Memory management for android applications
 
Detecting Memory Leaks in Android App
Detecting Memory Leaks in Android AppDetecting Memory Leaks in Android App
Detecting Memory Leaks in Android App
 
Detect all memory leaks with LeakCanary!
 Detect all memory leaks with LeakCanary! Detect all memory leaks with LeakCanary!
Detect all memory leaks with LeakCanary!
 
LCA13: Memory Hotplug on Android
LCA13: Memory Hotplug on AndroidLCA13: Memory Hotplug on Android
LCA13: Memory Hotplug on Android
 
Memory management in Android
Memory management in AndroidMemory management in Android
Memory management in Android
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in Andoid
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment Communication
 
Memory leak analyse
Memory leak analyseMemory leak analyse
Memory leak analyse
 
Facebook interview questions
Facebook interview questionsFacebook interview questions
Facebook interview questions
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
 
Android Data Binding
Android Data BindingAndroid Data Binding
Android Data Binding
 
RetroFit by Square - GDG Dallas 06/09/16
RetroFit by Square - GDG Dallas 06/09/16RetroFit by Square - GDG Dallas 06/09/16
RetroFit by Square - GDG Dallas 06/09/16
 
GKAC 2015 Apr. - Xamarin forms, mvvm and testing
GKAC 2015 Apr. - Xamarin forms, mvvm and testingGKAC 2015 Apr. - Xamarin forms, mvvm and testing
GKAC 2015 Apr. - Xamarin forms, mvvm and testing
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchas
 
GKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android LooperGKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android Looper
 

Similar to Android - Preventing common memory leaks

Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answersbestonlinetrainers
 
How to ace your .NET technical interview :: .Net Technical Check Tuneup
How to ace your .NET technical interview :: .Net Technical Check TuneupHow to ace your .NET technical interview :: .Net Technical Check Tuneup
How to ace your .NET technical interview :: .Net Technical Check TuneupBala Subra
 
Concurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and GotchasConcurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and Gotchasamccullo
 
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docxNJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docxcurwenmichaela
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsMike Wilcox
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction AKR Education
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answersKrishnaov
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performanceRoger Xia
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questionsnicolbiden
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questionsArun Banotra
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 

Similar to Android - Preventing common memory leaks (20)

Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
 
How to ace your .NET technical interview :: .Net Technical Check Tuneup
How to ace your .NET technical interview :: .Net Technical Check TuneupHow to ace your .NET technical interview :: .Net Technical Check Tuneup
How to ace your .NET technical interview :: .Net Technical Check Tuneup
 
Concurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and GotchasConcurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and Gotchas
 
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docxNJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
NJB_Coll_Lib1javadocallclasses-frame.htmlAll ClassesDynamicArr.docx
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
J2SE 5
J2SE 5J2SE 5
J2SE 5
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Java mcq
Java mcqJava mcq
Java mcq
 
Java Quiz - Meetup
Java Quiz - MeetupJava Quiz - Meetup
Java Quiz - Meetup
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 

Recently uploaded

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 

Recently uploaded (20)

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 

Android - Preventing common memory leaks

  • 1. Preventing memory leaks Ali Muzaffar
  • 2. Common causes of memory leaks  Which Context to use?  Application Context  Activity Context  Problem with references outside of context  Why should Handlers be static?  Should inner classes be static?  Recycle bitmaps
  • 3. Common causes of memory leaks  Which Context to use?  Application Context  Activity Context  Problem with references outside of context  Why should Handlers be static?  Should inner classes be static?  Leaking Threads  Also, Recycling Bitmaps (not covered here).
  • 4. Which Context? Which is better? 1. new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); 2. new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, list); 3. new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, list); 1. new TextView(this); 2. new TextView(getApplicationContext()); 3. new TextView(getBaseContext());
  • 5. Which is better? 1. new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); 2. new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, list); 3. new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, list); 1. new TextView(this); 2. new TextView(getApplicationContext()); 3. new TextView(getBaseContext());
  • 6. Good rule of thumb  Always use Application Context.  Use Activity where necessary. Meaning the object will be collected with the Activity or method specifically requests it.  Never use getBaseContext().
  • 7. Problem with references outside context  Why using the right context is important?  Threads & Garbage Collection  How do we fix this?
  • 8. Usually not a problem @Override protected void onCreate(Bundle state) { super.onCreate(state); TextView label = new TextView(this); label.setText("Leaks are bad"); setContentView(label); } //Code by Romain Guy
  • 9. Now it’s a problem private static Drawable sBackground; @Override protected void onCreate(Bundle state) { super.onCreate(state); TextView label = new TextView(this); label.setText("Leaks are bad"); if (sBackground == null) { sBackground = getDrawable(R.drawable.large_bitmap); } label.setBackgroundDrawable(sBackground); setContentView(label); } //Code by Romain Guy Drawables hold references to the Activity. TextView holds a strong reference to the Activity. The Drawable is not garbage collected, as a result, neither is the TextView or the Activity.
  • 10. The problem with non-static inner classes  Why do I get this error?
  • 12. So whats the issue with non-static inner classes  When an Android application first starts, the framework creates a Looper object for the application's main thread. A Looper implements a simple message queue, processing Message objects in a loop one after another. All major application framework events (such as Activity lifecycle method calls, button clicks, etc.) are contained inside Message objects, which are added to the Looper's message queue and are processed one-by-one. The main thread's Looper exists throughout the application's lifecycle.  When a Handler is instantiated on the main thread, it is associated with the Looper's message queue. Messages posted to the message queue will hold a reference to the Handler so that the framework can call Handler#handleMessage(Message) when the Looper eventually processes the message.  In Java, non-static inner and anonymous classes hold an implicit reference to their outer class. Static inner classes, on the other hand, do not.
  • 13. So what’s the issue with Threads?  Threads can be leaked along with/without memory.  Why?  Threads in Java are GC roots; that is, the Dalvik Virtual Machine (DVM) keeps hard references to all active threads in the runtime system, and as a result, threads that are left running will never be eligible for garbage collection.
  • 14. Crouton  Why do we have to call Crouton.cancelAllCroutons() ?
  • 15. Crouton  Why do we have to call Crouton.cancelAllCroutons() ?
  • 16. What can we do?  Do not reference anything outside of it’s scope.  Try to not have long living objects.  Don’t assume java will clean up your threads.  Implement cancellation policies for background threads.  WeakReference