Fixing Memory Leaks in Android Applications using DDMS & MAT Presented by Sravankumar Reddy Javaji CS286 Mobile Programming.

Slides:



Advertisements
Similar presentations
6 Copyright © 2005, Oracle. All rights reserved. Building Applications with Oracle JDeveloper 10g.
Advertisements

Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
NEXT. Create Pages in Blogger Another top user-requested feature has just graduated from Blogger In Draft! Blogger now makes it easy to create Pages linked.
CSC 213 – Large Scale Programming. Today’s Goals  Consider what new does & how Java works  What are traditional means of managing memory?  Why did.
Using Eclipse. Getting Started There are three ways to create a Java project: 1:Select File > New > Project, 2 Select the arrow of the button in the upper.
Android Tools & Wireless ADB Αντρέας Λύμπουρας Θεόφιλος Φωκάς Ζαχαρίας Χ’’Λάμπρου.
MCTS GUIDE TO MICROSOFT WINDOWS 7 Chapter 10 Performance Tuning.
Memory issues in production systems. Production system Restricted access Application, DB, Application server, log files Debugging, monitoring Investigation.
Hastings Purify: Fast Detection of Memory Leaks and Access Errors.
Android: Managing Memory
Using Folders to Organize Files
Calendar Browser is a groupware used for booking all kinds of resources within an organization. Calendar Browser is installed on a file server and in a.
CPSC 388 – Compiler Design and Construction
On the limits of partial compaction Anna Bendersky & Erez Petrank Technion.
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
Chapter 11 - Monitoring Server Performance1 Ch. 11 – Monitoring Server Performance MIS 431 – created Spring 2006.
Debugging Android Applications
WINDOWS XP BACKNEXTEND 1-1 LINKS TO OBJECTIVES Starting Windows Using the Taskbar, opening & switching programs Using the Taskbar, opening & switching.
ANDROID PROGRAMMING MODULE 1 – GETTING STARTED
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
Tips and tricks for maximizing Windows 7. The Start menu New streamlined design No more “My” Recently programs now sport Jump Lists All Programs menu.
1 Agenda Overview Review Roles Lists Libraries Columns.
Control and monitoring of on-line trigger algorithms using a SCADA system Eric van Herwijnen Wednesday 15 th February 2006.
Programming with App Inventor Computing Institute for K-12 Teachers Summer 2012 Workshop.
Of Bytes, Cycles and Battery Life. Who am [2] [1]
CLR: Garbage Collection Inside Out
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2012 CHAPTER TWELVE (ENRICHMENT CHAPTER) Windows Store Apps.
Project 3 File, Document, Folder Management, Windows XP Explorer Windows XP Service Pack 2 Edition Comprehensive Concepts and Techniques.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
MCTS Guide to Microsoft Windows 7
Create Database Tables
Dynamic Memory Allocation Questions answered in this lecture: When is a stack appropriate? When is a heap? What are best-fit, first-fit, worst-fit, and.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
CIS—100 Chapter 15—Windows Vista 1. Parts of a Window 2.
LiveCycle Data Services Introduction Part 2. Part 2? This is the second in our series on LiveCycle Data Services. If you missed our first presentation,
Chapter 2 Working with Disks and Other Removable Media 2.
Author: Loh Jianxiong Christopher Editors: Chua Jie Sheng, Li Mengran, Peh Shao Hong, Oo Theong Siang.
Understanding Perfmon The Performance Testing Tool >>>>>>>>>>>>>>>>>>>>>>
1 The EDIT Program The Edit program is a full screen text editor that allows you to: Create text files Create text files Edit an existing text files Edit.
Computing Fundamentals Module Lesson 3 — Changing Settings and Customizing the Desktop Computer Literacy BASICS.
Mobile Application Optimization. Sanath Nandasiri Programmer.(Not a singer) (Exilesoft)
Problem of the Day  Why are manhole covers round?
Support.ebsco.com Introduction to EBSCOhost Tutorial.
Working with Graphics – Lesson 21 Working with Graphics Lesson 2.
Chapter 10 Chapter 10: Managing the Distributed File System, Disk Quotas, and Software Installation.
Click to add text © 2012 IBM Corporation Design Manager Server Instrumentation Instrumentation Data Documentation Gary Johnston, Performance Focal Point,
Android Studio IDE Tools Operation Summary. icle.html icle.html.
I. Getting Started with the Interface Microsoft ® Windows ® Movie Maker.
Bit-DSP-MicrocontrollerTMS320F2812 Texas Instruments Incorporated European Customer Training Center University of Applied Sciences Zwickau (FH)
Mobile Programming Lecture 3 Debugging. Lecture 2 Review What widget would you use to allow the user to enter o a yes/no value o a range of values from.
Garbage Collection and Classloading Java Garbage Collectors  Eden Space  Surviver Space  Tenured Gen  Perm Gen  Garbage Collection Notes Classloading.
Author: Loh Jianxiong Christopher Contributions: Chua Jie Sheng, Li Mengran, Peh Shao Hong, Oo Theong Siang, Tong Chun Kit, Tania Chattopadhyay.
Work with Tables and Database Records Lesson 3. NAVIGATING AMONG RECORDS Access users who prefer using the keyboard to navigate records can press keys.
Transportation Agenda 187. Transportation About Web Parts Web parts are reusable “containers” that reside on web pages and interact with lists, libraries.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
Chapter 7 Creating Templates, Importing Data, and Working with SmartArt, Images, and Screen Shots Microsoft Excel 2013.
How to Use an Android Tablet Well Come To You few Steps For How to Use an Android Tablet?
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
3 Important Performance tracking tools in an Android Application Development Workflow Here are 3 tools every Android application developer should familiarize.
Memory Management for Android Apps Min Ji, Kim Embedded Software Lab.
Debugging with Eclipse
Computer Literacy BASICS
MCTS Guide to Microsoft Windows 7
Using Procedures and Exception Handling
Introduction to EBSCOhost
These slides are for reference only. They are not "lecture notes"
Mobile Programming Dr. Mohsin Ali Memon.
Presentation transcript:

Fixing Memory Leaks in Android Applications using DDMS & MAT Presented by Sravankumar Reddy Javaji CS286 Mobile Programming

HTC Dream (2008) 192 MB Ram 320×480 display Nexus 5 (2013) 2 GB Ram 1920x1080 display Evolution of Devices

Heap Size Heap size is limited and device dependent  G1 = 16 Mb  Droid = 24 Mb  Nexus One = 32 Mb  Xoom = 48 Mb  GalaxyTab = 64 Mb. ActivityManager.getMemoryClass()

Pre-defined heap-size settings are specified in /system/build.prop file for each device.  dalvik.vm.heapstartsize=5m  dalvik.vm.heapgrowthlimit=48m  dalvik.vm.heapsize=128m  dalvik.vm.heaptargetutilization=0.75  dalvik.vm.heapminfree=512k  dalvik.vm.heapmaxfree=2m in-system-build-prop Heap Size..contd..

Honeycomb adds “largeHeap” option in AndroidManifest.xml: - Degrades performance! Use only if you understand why you need it. <application android:name="com.example.foobar" android:largeHeap="true"... ActivityManager.getLargeMemoryClass() Large Heaps

A larger memory heap  Allows more objects to be created  Takes longer to fill  Allows the application to run longer between garbage collection (GC) events A smaller memory heap  Holds fewer objects  Fills more quickly  Is garbage collected more frequently (but the pauses are shorter)  May lead to out-of-memory errors The more memory we use, the more work GC has, the more work GC has the bigger pause will be. Battery life larger heap VS smaller heap

Finding out when the Garbage Collection is run? - Search for 'GC' or 'gc' in LogCat How to trigger the Garbage Collection manually? - System.gc(); Mark and sweep is one of the earliest and best-known garbage collection algorithms. Garbage Collection

Mark and Sweep Algorithm GC Roots A E D G H B F C

Mark and Sweep Algorithm GC Roots A E D G H B F C

Mark and Sweep Algorithm GC Roots A E D G H B F C

Mark and Sweep Algorithm GC Roots A E D G H B F C

Changes in Garbage Collection Pre-Gingerbread GC: – Stop-the-world – Full heap collection – Large Pause Times. Pause times often > 100ms Gingerbread and beyond: – Advantage of multi-core support. Concurrent (mostly) – Partial collections – Smaller pause times. Pause times usually < 5ms

Bitmaps Bitmaps take up a lot of memory, especially for rich images like photographs. For example, the camera on the Galaxy Nexus takes photos up to 2592x1936 pixels (5 megapixels). Loading this image into memory takes about 19MB of memory (2592*1936*4 bytes). If you're not careful, bitmaps can quickly consume your available memory budget leading to an application crash due to the dreaded exception: java.lang.OutofMemoryError: bitmap size exceeds VM budget.

Managing Bitmap Memory Old way (pre-Honeycomb): – Bitmaps are saved in Native memory. Freed via recycle() or finalizer – hard to debug – full, stop-the-world GCs New way: – Bitmaps are saved in Managed (Heap) memory. Freed synchronously by GC – easier to debug – concurrent & partial GCs

Understanding heap usage – DDMS (Dalvik Debug Monitor Server) – Eclipse Memory Analyzer (MAT)

Debugging a memory leak Let's walk through an example using the Honeycomb Gallery sample app from the Android SDK. We're going to deliberately add a memory leak to this app in order to demonstrate how it could be debugged. Lets implement a cache in this app which holds recently-viewed images by making a few small changes to ContentFragment.java.

Debugging a memory leak..contd.. At the top of the class, let's add a new static variable: private static HashMap sBitmapCache = new HashMap (); This is where we'll cache the Bitmaps that we load. Now we can change the updateContentAndRecycleBitmap() method to check the cache before loading, and to add Bitmaps to the cache after they're loaded. void updateContentAndRecycleBitmap(int category, int position) { if (mCurrentActionMode != null) { mCurrentActionMode.finish(); }

Debugging a memory leak..contd.. // Get the bitmap that needs to be drawn and update the ImageView. // Check if the Bitmap is already in the cache String bitmapId = "" + category + "." + position; mBitmap = sBitmapCache.get(bitmapId); if (mBitmap == null) { // It's not in the cache, so load the Bitmap and add it to the cache. // DANGER! We add items to this cache without ever removing any. mBitmap = Directory.getCategory(category).getEntry(position).getBitmap(getResources()); sBitmapCache.put(bitmapId, mBitmap); } ((ImageView) getView().findViewById(R.id.image)).setImageBitmap(mBitmap); }

Debugging a memory leak..contd.. What is Memory Leak here? We added Bitmaps to the cache without ever removing them. In a real app, we'd probably want to limit the size of the cache in some way.

Examining heap usage in DDMS Select the process com.example.android.hcgallery in the left pane, and then click the Show heap updates button in the toolbar. Then, switch to the VM Heap tab in DDMS. It shows some basic stats about our heap memory usage, updated after every GC. To see the first update, click the Cause GC button. We can see that our live set (the Allocated column) is a little over 8MB. Now flip through the photos, and watch that number go up. Since there are only 13 photos in this app, the amount of memory we leak is bounded. In some ways, this is the worst kind of leak to have, because we never get an OutOfMemoryError indicating that we are leaking.

Examining heap usage in DDMS

1 2 Creating a heap dump

Click on Histogram view Analyzing heap dumps using MAT

The Histogram view shows a list of classes sortable by the number of instances, the shallow heap or the retained heap.

Analyzing heap dumps using MAT If we sort by shallow heap, we can see that instances of byte[] are at the top. As of Android 3.0 (Honeycomb), the pixel data for Bitmap objects is stored in byte arrays (previously it was not stored in the Dalvik heap), and based on the size of these objects, it's a safe bet that they are the backing memory for our leaked bitmaps. Right-click on the byte[] class and select List Objects > with incoming references. This produces a list of all byte arrays in the heap, which we can sort based on Shallow Heap usage. Pick one of the big objects, and drill down on it. This will show you the path from the root set to the object -- the chain of references that keeps this object alive. Lo and behold, there's our bitmap cache!

Analyzing heap dumps using MAT Culprit

Comparing heap dumps with MAT We need to create two separate HPROF files. Open the first HPROF file (if it is not already opened) Open the Histogram view. Open the second HPROF file. Switch to first HPROF file's Histogram view and click “compare to another Heap Dump” Icon. Then a window will be prompted to select a heap dump from the open editors as baseline. Select second HPROF file and press OK.

Comparing heap dumps with MAT..contd..

Downloading MAT MAT for Eclipse IDE:- Standalone MAT:-

References apps/ memory.html memory-leaks.html mslogcatmemoryoutputmessages causes-in-java.html

Queries. ?

Thank You. !