SlideShare a Scribd company logo
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!
Ad

More Related Content

What's hot (19)

Class method object
Class method objectClass method object
Class method object
Minal Maniar
 
Android concurrency
Android concurrencyAndroid concurrency
Android concurrency
Ruslan Novikov
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
xuehan 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 java
Talha Ocakçı
 
Java memory model
Java memory modelJava memory model
Java memory model
Rushan Arunod
 
JProfiler8 @ OVIRT
JProfiler8 @ OVIRTJProfiler8 @ OVIRT
JProfiler8 @ OVIRT
Liran 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 Class
CODE 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 future
Sander Mak (@Sander_Mak)
 
Exception handling
Exception handlingException handling
Exception handling
Minal 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 2016
Christian 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 Practice
Alina Dolgikh
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
Somenath Mukhopadhyay
 
Memory Leak In java
Memory Leak In javaMemory Leak In java
Memory Leak In java
Mindfire Solutions
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
Ganesh Samarthyam
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Maulik Shah
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Hoang Nguyen
 
Class method object
Class method objectClass method object
Class method object
Minal Maniar
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
xuehan 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 java
Talha Ocakçı
 
JProfiler8 @ OVIRT
JProfiler8 @ OVIRTJProfiler8 @ OVIRT
JProfiler8 @ OVIRT
Liran 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 Class
CODE 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 future
Sander Mak (@Sander_Mak)
 
Exception handling
Exception handlingException handling
Exception handling
Minal 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 2016
Christian 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 Practice
Alina Dolgikh
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
Somenath Mukhopadhyay
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Maulik Shah
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Hoang Nguyen
 

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
Zachary Blair
 
Memory leak
Memory leakMemory leak
Memory leak
Anandraj Kulkarni
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android Applications
Lokesh Ponnada
 
lightning talk : Android memory leak
lightning talk :  Android memory leaklightning talk :  Android memory leak
lightning talk : Android memory leak
Deivison Sporteman
 
Memory management for_android_apps
Memory management for_android_appsMemory management for_android_apps
Memory management for_android_apps
Bin 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 applications
AiTi Education
 
Detecting Memory Leaks in Android App
Detecting Memory Leaks in Android AppDetecting Memory Leaks in Android App
Detecting Memory Leaks in Android App
Dinesh 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 Android
Linaro
 
Memory management in Android
Memory management in AndroidMemory management in Android
Memory management in Android
Keyhan Asghari
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in Andoid
Monkop Inc
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment Communication
CITSimon
 
Memory leak analyse
Memory leak analyseMemory leak analyse
Memory leak analyse
Bernd Zuther
 
Facebook interview questions
Facebook interview questionsFacebook interview questions
Facebook interview questions
Sumit 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 Kumpera
Xamarin
 
Android Data Binding
Android Data BindingAndroid Data Binding
Android Data Binding
Ezequiel Zanetta
 
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
Stacy 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 testing
GDG Korea
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchas
Alec Tucker
 
GKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android LooperGKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android Looper
GDG Korea
 
Identifying memory leaks in Android applications
Identifying memory leaks in Android applicationsIdentifying memory leaks in Android applications
Identifying memory leaks in Android applications
Zachary Blair
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android Applications
Lokesh Ponnada
 
lightning talk : Android memory leak
lightning talk :  Android memory leaklightning talk :  Android memory leak
lightning talk : Android memory leak
Deivison Sporteman
 
Memory management for_android_apps
Memory management for_android_appsMemory management for_android_apps
Memory management for_android_apps
Bin 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 applications
AiTi Education
 
Detecting Memory Leaks in Android App
Detecting Memory Leaks in Android AppDetecting Memory Leaks in Android App
Detecting Memory Leaks in Android App
Dinesh 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 Android
Linaro
 
Memory management in Android
Memory management in AndroidMemory management in Android
Memory management in Android
Keyhan Asghari
 
Memory management in Andoid
Memory management in AndoidMemory management in Andoid
Memory management in Andoid
Monkop Inc
 
Spinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment CommunicationSpinners, Adapters & Fragment Communication
Spinners, Adapters & Fragment Communication
CITSimon
 
Memory leak analyse
Memory leak analyseMemory leak analyse
Memory leak analyse
Bernd Zuther
 
Facebook interview questions
Facebook interview questionsFacebook interview questions
Facebook interview questions
Sumit 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 Kumpera
Xamarin
 
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
Stacy 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 testing
GDG Korea
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchas
Alec Tucker
 
GKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android LooperGKAC 2015 Apr. - Android Looper
GKAC 2015 Apr. - Android Looper
GDG Korea
 
Ad

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
bestonlinetrainers
 
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
Bala 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 Gotchas
amccullo
 
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
curwenmichaela
 
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
StephieJohn
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
Mike 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
 
J2SE 5
J2SE 5J2SE 5
J2SE 5
Luqman Shareef
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
Krishnaov
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
dwm042
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
Roger Xia
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
nicolbiden
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
Arun Banotra
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Naresh Jain
 
Java mcq
Java mcqJava mcq
Java mcq
avinash9821
 
Java Quiz - Meetup
Java Quiz - MeetupJava Quiz - Meetup
Java Quiz - Meetup
CodeOps Technologies LLP
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
Lokesh Singrol
 
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
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
G C Reddy Technologies
 
Java interview-questions-and-answers
Java interview-questions-and-answersJava interview-questions-and-answers
Java interview-questions-and-answers
bestonlinetrainers
 
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
Bala 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 Gotchas
amccullo
 
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
curwenmichaela
 
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
StephieJohn
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
Mike 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 Dom
kaven yan
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
Krishnaov
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
dwm042
 
Java programing considering performance
Java programing considering performanceJava programing considering performance
Java programing considering performance
Roger Xia
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
nicolbiden
 
25 java tough interview questions
25 java tough interview questions25 java tough interview questions
25 java tough interview questions
Arun Banotra
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Naresh 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
 
Ad

Recently uploaded (20)

Drawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon Creation
Drawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon CreationDrawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon Creation
Drawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon Creation
Philip Schwarz
 
Top Reasons to Hire Dedicated Odoo Developers for Your ERP Project
Top Reasons to Hire Dedicated Odoo Developers for Your ERP ProjectTop Reasons to Hire Dedicated Odoo Developers for Your ERP Project
Top Reasons to Hire Dedicated Odoo Developers for Your ERP Project
Kanak Infosystems LLP.
 
Call of Duty: Warzone for Windows With Crack Free Download 2025
Call of Duty: Warzone for Windows With Crack Free Download 2025Call of Duty: Warzone for Windows With Crack Free Download 2025
Call of Duty: Warzone for Windows With Crack Free Download 2025
Iobit Uninstaller Pro Crack
 
Nasdanika Overview - Mission, Vision, Differentiators & Capabilities
Nasdanika Overview - Mission, Vision, Differentiators & CapabilitiesNasdanika Overview - Mission, Vision, Differentiators & Capabilities
Nasdanika Overview - Mission, Vision, Differentiators & Capabilities
Pavel Vlasov
 
OpenMetadata Spotlight - OpenMetadata @ EDNON
OpenMetadata Spotlight - OpenMetadata @ EDNONOpenMetadata Spotlight - OpenMetadata @ EDNON
OpenMetadata Spotlight - OpenMetadata @ EDNON
OpenMetadata
 
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdfCFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
Ortus Solutions, Corp
 
Web Application Development A Comprehensive Guide for 2025.pdf
Web Application Development A Comprehensive Guide for 2025.pdfWeb Application Development A Comprehensive Guide for 2025.pdf
Web Application Development A Comprehensive Guide for 2025.pdf
Secuodsoft
 
AI Agents with Gemini 2.0 - Beyond the Chatbot
AI Agents with Gemini 2.0 - Beyond the ChatbotAI Agents with Gemini 2.0 - Beyond the Chatbot
AI Agents with Gemini 2.0 - Beyond the Chatbot
Márton Kodok
 
Choose Your Own Adventure to Get Started with Grafana Loki
Choose Your Own Adventure to Get Started with Grafana LokiChoose Your Own Adventure to Get Started with Grafana Loki
Choose Your Own Adventure to Get Started with Grafana Loki
Imma Valls Bernaus
 
Lightworks PRO 2025.1 Crack Free Download
Lightworks PRO 2025.1 Crack Free DownloadLightworks PRO 2025.1 Crack Free Download
Lightworks PRO 2025.1 Crack Free Download
Berkeley
 
Why Exceptions are just sophisticated GoTos ... and How to Move Beyond
Why Exceptions are just sophisticated GoTos ... and How to Move BeyondWhy Exceptions are just sophisticated GoTos ... and How to Move Beyond
Why Exceptions are just sophisticated GoTos ... and How to Move Beyond
Florian Wilhelm
 
Modern Software Testing Playwright, Gen AI, and Machine Learning Models for E...
Modern Software Testing Playwright, Gen AI, and Machine Learning Models for E...Modern Software Testing Playwright, Gen AI, and Machine Learning Models for E...
Modern Software Testing Playwright, Gen AI, and Machine Learning Models for E...
Venkatesh (Rahul Shetty)
 
Salesforce CRM and software as service model.pdf
Salesforce CRM and software as service model.pdfSalesforce CRM and software as service model.pdf
Salesforce CRM and software as service model.pdf
rinakali1
 
TUG Brazil - VizQL Data Service - Nik Dutra.pdf
TUG Brazil - VizQL Data Service - Nik Dutra.pdfTUG Brazil - VizQL Data Service - Nik Dutra.pdf
TUG Brazil - VizQL Data Service - Nik Dutra.pdf
Ligia Galvão
 
CYB 305 Forensics and Digital Computer Security.pptx
CYB 305  Forensics and Digital Computer Security.pptxCYB 305  Forensics and Digital Computer Security.pptx
CYB 305 Forensics and Digital Computer Security.pptx
Muhammad54342
 
LightBurn 1.7.0.6 + Crack Download🔓
LightBurn  1.7.0.6  +  Crack  Download🔓LightBurn  1.7.0.6  +  Crack  Download🔓
LightBurn 1.7.0.6 + Crack Download🔓
Berkeley
 
15 Years of Insights from a TDD Practitioner (NDC Oslo)
15 Years of Insights from a TDD Practitioner (NDC Oslo)15 Years of Insights from a TDD Practitioner (NDC Oslo)
15 Years of Insights from a TDD Practitioner (NDC Oslo)
Dennis Doomen
 
upload_to_ss_open-LLM-Security-Benchmark.pdf
upload_to_ss_open-LLM-Security-Benchmark.pdfupload_to_ss_open-LLM-Security-Benchmark.pdf
upload_to_ss_open-LLM-Security-Benchmark.pdf
avreyjeyson
 
Daily Agile Snippets That Boost Team Focus and Flexibility
Daily Agile Snippets That Boost Team Focus and FlexibilityDaily Agile Snippets That Boost Team Focus and Flexibility
Daily Agile Snippets That Boost Team Focus and Flexibility
Orangescrum
 
Shift Right Security for EKS Webinar Slides
Shift Right Security for EKS Webinar SlidesShift Right Security for EKS Webinar Slides
Shift Right Security for EKS Webinar Slides
Anchore
 
Drawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon Creation
Drawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon CreationDrawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon Creation
Drawing Heighway’s Dragon - Part 4 - Interactive and Animated Dragon Creation
Philip Schwarz
 
Top Reasons to Hire Dedicated Odoo Developers for Your ERP Project
Top Reasons to Hire Dedicated Odoo Developers for Your ERP ProjectTop Reasons to Hire Dedicated Odoo Developers for Your ERP Project
Top Reasons to Hire Dedicated Odoo Developers for Your ERP Project
Kanak Infosystems LLP.
 
Call of Duty: Warzone for Windows With Crack Free Download 2025
Call of Duty: Warzone for Windows With Crack Free Download 2025Call of Duty: Warzone for Windows With Crack Free Download 2025
Call of Duty: Warzone for Windows With Crack Free Download 2025
Iobit Uninstaller Pro Crack
 
Nasdanika Overview - Mission, Vision, Differentiators & Capabilities
Nasdanika Overview - Mission, Vision, Differentiators & CapabilitiesNasdanika Overview - Mission, Vision, Differentiators & Capabilities
Nasdanika Overview - Mission, Vision, Differentiators & Capabilities
Pavel Vlasov
 
OpenMetadata Spotlight - OpenMetadata @ EDNON
OpenMetadata Spotlight - OpenMetadata @ EDNONOpenMetadata Spotlight - OpenMetadata @ EDNON
OpenMetadata Spotlight - OpenMetadata @ EDNON
OpenMetadata
 
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdfCFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
CFCamp2025 - Keynote Day 1 led by Luis Majano.pdf
Ortus Solutions, Corp
 
Web Application Development A Comprehensive Guide for 2025.pdf
Web Application Development A Comprehensive Guide for 2025.pdfWeb Application Development A Comprehensive Guide for 2025.pdf
Web Application Development A Comprehensive Guide for 2025.pdf
Secuodsoft
 
AI Agents with Gemini 2.0 - Beyond the Chatbot
AI Agents with Gemini 2.0 - Beyond the ChatbotAI Agents with Gemini 2.0 - Beyond the Chatbot
AI Agents with Gemini 2.0 - Beyond the Chatbot
Márton Kodok
 
Choose Your Own Adventure to Get Started with Grafana Loki
Choose Your Own Adventure to Get Started with Grafana LokiChoose Your Own Adventure to Get Started with Grafana Loki
Choose Your Own Adventure to Get Started with Grafana Loki
Imma Valls Bernaus
 
Lightworks PRO 2025.1 Crack Free Download
Lightworks PRO 2025.1 Crack Free DownloadLightworks PRO 2025.1 Crack Free Download
Lightworks PRO 2025.1 Crack Free Download
Berkeley
 
Why Exceptions are just sophisticated GoTos ... and How to Move Beyond
Why Exceptions are just sophisticated GoTos ... and How to Move BeyondWhy Exceptions are just sophisticated GoTos ... and How to Move Beyond
Why Exceptions are just sophisticated GoTos ... and How to Move Beyond
Florian Wilhelm
 
Modern Software Testing Playwright, Gen AI, and Machine Learning Models for E...
Modern Software Testing Playwright, Gen AI, and Machine Learning Models for E...Modern Software Testing Playwright, Gen AI, and Machine Learning Models for E...
Modern Software Testing Playwright, Gen AI, and Machine Learning Models for E...
Venkatesh (Rahul Shetty)
 
Salesforce CRM and software as service model.pdf
Salesforce CRM and software as service model.pdfSalesforce CRM and software as service model.pdf
Salesforce CRM and software as service model.pdf
rinakali1
 
TUG Brazil - VizQL Data Service - Nik Dutra.pdf
TUG Brazil - VizQL Data Service - Nik Dutra.pdfTUG Brazil - VizQL Data Service - Nik Dutra.pdf
TUG Brazil - VizQL Data Service - Nik Dutra.pdf
Ligia Galvão
 
CYB 305 Forensics and Digital Computer Security.pptx
CYB 305  Forensics and Digital Computer Security.pptxCYB 305  Forensics and Digital Computer Security.pptx
CYB 305 Forensics and Digital Computer Security.pptx
Muhammad54342
 
LightBurn 1.7.0.6 + Crack Download🔓
LightBurn  1.7.0.6  +  Crack  Download🔓LightBurn  1.7.0.6  +  Crack  Download🔓
LightBurn 1.7.0.6 + Crack Download🔓
Berkeley
 
15 Years of Insights from a TDD Practitioner (NDC Oslo)
15 Years of Insights from a TDD Practitioner (NDC Oslo)15 Years of Insights from a TDD Practitioner (NDC Oslo)
15 Years of Insights from a TDD Practitioner (NDC Oslo)
Dennis Doomen
 
upload_to_ss_open-LLM-Security-Benchmark.pdf
upload_to_ss_open-LLM-Security-Benchmark.pdfupload_to_ss_open-LLM-Security-Benchmark.pdf
upload_to_ss_open-LLM-Security-Benchmark.pdf
avreyjeyson
 
Daily Agile Snippets That Boost Team Focus and Flexibility
Daily Agile Snippets That Boost Team Focus and FlexibilityDaily Agile Snippets That Boost Team Focus and Flexibility
Daily Agile Snippets That Boost Team Focus and Flexibility
Orangescrum
 
Shift Right Security for EKS Webinar Slides
Shift Right Security for EKS Webinar SlidesShift Right Security for EKS Webinar Slides
Shift Right Security for EKS Webinar Slides
Anchore
 

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
  翻译: