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!

More Related Content

What's hot

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
 
Incident Resolution as Code
Incident Resolution as CodeIncident Resolution as Code
Incident Resolution as Code
Julien Pivotto
 
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
 
Java Memory Model
Java Memory ModelJava Memory Model
Java Memory Model
*instinctools
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Maulik 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 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_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 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 analyseBernd 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 KumperaXamarin
 
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
 

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-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
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
 

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

Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaTop 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Yara Milbes
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 

Recently uploaded (20)

Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaTop 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 

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