SlideShare a Scribd company logo
Memory Management



   Kuban Dzhakipov
      @Sibers
         2012
Plan

● introduction
● fundamentals
● solutions via WeakReference, SoftReference, etc
● analyze tools
Memory Usage
8 primitive data types:
Integers:
  ● byte
  ● short - 2 bytes
  ● int - 4 bytes
  ● long - 8 bytes
Floating-point number:
  ● float 4 bytes
  ● double 8 bytes
Characters:
  ● char - 2 bytes (utf16)
Boolean
  ● boolean - 1 byte (1 byte versus 1 bit, alternative BitSet)
Memory Usage
Object Shallow size = object header + object fields

Object header:
  ● Hash Code
  ● Garbage Collection Information
  ● Type Information Block Pointer
  ● Lock
  ● ArrayLength

object header size:
* 32bit - 8 bytes
* 64bit - 16 bytes
Memory Usage

 1.   public final class String { //8 bytes
 2.   private char value[]; // 4 bytes
 3.   private int offset; // 4bytes
 4.   private int count; //4 bytes
 5.   private int hash; //4 bytes
 6.   }
 7.
 8.   // Shallow size of a String = 24 bytes
 9.   // Davlik VM for ARM
10.
11.   * 32 bit architecture
Memory Usage

new String() // 24 bytes
new String("a") // 40 bytes

new char[1]
Object Header: 12 bytes
Data type char: 2 bytes
Offset : 2 bytes
Total: 16 bytes

new String("a") == 40 bytes


* 32 bit architecture
* 64 bit architecture = 40+16=56bytes
GC
Memory management
GC

 1.   for(int z=0; z < 10000; z++){
 2.      SomeClass a = new SomeClass();
 3.      a.doSomething();
 4.      for(int i=0; i<100;i++; i++){
 5.           StringBuilder str = new StringBuilder();
 6.           str.append("This is #");
 7.           str.append(i);
 8.           System.out.println(str.toString());
 9.       }
10.   }
11.   .......
12.   // collects objects by gc
Memory Leak
  1.   // example #1
  2.   ArrayList least = new ArrayList();
  3.   for(int i=0; i<10000; i++){
  4.      String n = "something"; // couldn't be destroyed by gc
  5.      least.add(n);
  6.   }
....* least is property of object

  7.   //example #2
  8.   @Override
  9.   protected void onCreate(Bundle state) {
 10.     super.onCreate(state);
 11.
 12.       TextView label = new TextView(this);
 13.       label.setText("Leaks are bad");
 14.
 15.       setContentView(label);
 16.   }
Memory Leak

              // strong reference
OutOfMemoryError?
Solutions

● SoftReference
● WeakReference
● PhantomReference
SoftReference

 1. SoftReference<List<Foo>> ref = new SoftReference<List<Foo>>
    (new LinkedList<Foo>()); // create some Foos, probably in a loop
 2. List<Foo> list = ref.get();
 3. if (list == null) throw new RuntimeException("ran out of memory");
 4. list.add(foo);
WeakReference

1. WeakReference<List<Foo>> ref = new WeakReference<List<Foo>>
   (new LinkedList<Foo>()); // create some Foos, probably in a loop
2. List<Foo> list = ref.get();
3. if (list == null) throw new RuntimeException("ran out of memory");
4. list.add(foo);
PhantomReference

 1. PhantomReference<List<Foo>> ref =
    new PhantomReference<List<Foo>>(new LinkedList<Foo>(), new ReferenceQueue<List<Foo>>());
    // create some Foos, probably in a loop
 2. List<Foo> list = ref.get(); // always return null
Memory Analyze Tool

JHat
JProfiler
Eclipse Memory Analyzer
Yourkit
Netbeans
Eclipse Memory Analyzer



Information available on
http://eclipse.org/mat/
Get a Heap

● jconsole
● jmap
● ddms(android)
Overview
Histogram
Dominator Tree
Path to GC Roots
GC Roots

The so-called GC (Garbage Collector) roots are objects special for garbage collector. Garbage collector collects those objects
that are not GC roots and are not accessible by references from GC roots.

There are several kinds of GC roots. One object can belong to more than one kind of root. The root kinds are:

    ●   Class - loaded class. Classes can hold objects via static fields.
    ●   Alive Threads
    ●   Stack Local - local variable or parameter of method.
    ●   Finalizer Queue Entry - object scheduled for finalization.
    ●   GC Handle - provides a means for accessing a managed object from unmanaged memory.
    ●   Other - objects hold from garbage collection by CLR for other reasons.
Summary
?
Thanks for your time!




                        Sources:
                        d.android.com
                        habrahabr.ru
                        eclipse.org/mat

More Related Content

PPT
Java 7
PPTX
RealmDB for Android
PPTX
Nicety of Java 8 Multithreading
PDF
Odoo Technical Concepts Summary
PDF
DConf 2016: Keynote by Walter Bright
PPTX
Javascript Execution Context Flow
PDF
MySQL Without The SQL -- Oh My! PHP Detroit July 2018
PDF
ooc - OSDC 2010 - Amos Wenger
Java 7
RealmDB for Android
Nicety of Java 8 Multithreading
Odoo Technical Concepts Summary
DConf 2016: Keynote by Walter Bright
Javascript Execution Context Flow
MySQL Without The SQL -- Oh My! PHP Detroit July 2018
ooc - OSDC 2010 - Amos Wenger

What's hot (20)

PPTX
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
PPTX
MongoDB
PPTX
DConf 2016: Bitpacking Like a Madman by Amaury Sechet
PPTX
TDD With Typescript - Noam Katzir
PPTX
Introduction to MongoDB
PPTX
Mongo db nosql (1)
PDF
RedisConf17 - Redis as a JSON document store
PDF
HexRaysCodeXplorer: object oriented RE for fun and profit
PDF
Active records before_type_cast
PDF
Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)
PPTX
Apache Spark - Aram Mkrtchyan
PPTX
Coding using jscript test complete
PDF
Ts archiving
PDF
24 uses for perl6
PDF
Using spark data frame for sql
PDF
HexRaysCodeXplorer: make object-oriented RE easier
PPTX
Log* with Cassandra
PDF
Java JVM Memory Cheat Sheet
PDF
Full Stack Clojure
PDF
Latinoware
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
MongoDB
DConf 2016: Bitpacking Like a Madman by Amaury Sechet
TDD With Typescript - Noam Katzir
Introduction to MongoDB
Mongo db nosql (1)
RedisConf17 - Redis as a JSON document store
HexRaysCodeXplorer: object oriented RE for fun and profit
Active records before_type_cast
Search Engine-Building with Lucene and Solr, Part 2 (SoCal Code Camp LA 2013)
Apache Spark - Aram Mkrtchyan
Coding using jscript test complete
Ts archiving
24 uses for perl6
Using spark data frame for sql
HexRaysCodeXplorer: make object-oriented RE easier
Log* with Cassandra
Java JVM Memory Cheat Sheet
Full Stack Clojure
Latinoware
Ad

Similar to Memory management (20)

PPTX
Why learn Internals?
PDF
Exploitation of counter overflows in the Linux kernel
PPTX
PDF
Save Java memory
PDF
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
PPTX
Scope Stack Allocation
PPTX
Php Extensions for Dummies
PPTX
Building High Perf Web Apps - IE8 Firestarter
PPT
Memory Optimization
PPT
Memory Optimization
KEY
JavaOne 2012 - JVM JIT for Dummies
PDF
55 new things in Java 7 - Devoxx France
PDF
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
PDF
Look Mommy, No GC! (TechDays NL 2017)
PDF
Blocks & GCD
PPTX
NET Systems Programming Learned the Hard Way.pptx
PDF
Kerberizing spark. Spark Summit east
PPTX
How to write memory efficient code?
PDF
Softshake - Offline applications
ODP
Drupal MySQL Cluster
Why learn Internals?
Exploitation of counter overflows in the Linux kernel
Save Java memory
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Scope Stack Allocation
Php Extensions for Dummies
Building High Perf Web Apps - IE8 Firestarter
Memory Optimization
Memory Optimization
JavaOne 2012 - JVM JIT for Dummies
55 new things in Java 7 - Devoxx France
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
Look Mommy, No GC! (TechDays NL 2017)
Blocks & GCD
NET Systems Programming Learned the Hard Way.pptx
Kerberizing spark. Spark Summit east
How to write memory efficient code?
Softshake - Offline applications
Drupal MySQL Cluster
Ad

Recently uploaded (20)

PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
STKI Israel Market Study 2025 version august
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
PDF
August Patch Tuesday
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PPT
Module 1.ppt Iot fundamentals and Architecture
PPTX
1. Introduction to Computer Programming.pptx
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PPTX
Tartificialntelligence_presentation.pptx
PPTX
OMC Textile Division Presentation 2021.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Hindi spoken digit analysis for native and non-native speakers
Programs and apps: productivity, graphics, security and other tools
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
DP Operators-handbook-extract for the Mautical Institute
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
STKI Israel Market Study 2025 version august
WOOl fibre morphology and structure.pdf for textiles
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Final SEM Unit 1 for mit wpu at pune .pptx
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
August Patch Tuesday
A novel scalable deep ensemble learning framework for big data classification...
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
NewMind AI Weekly Chronicles – August ’25 Week III
Module 1.ppt Iot fundamentals and Architecture
1. Introduction to Computer Programming.pptx
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Tartificialntelligence_presentation.pptx
OMC Textile Division Presentation 2021.pptx
Group 1 Presentation -Planning and Decision Making .pptx
Hindi spoken digit analysis for native and non-native speakers

Memory management

  • 1. Memory Management Kuban Dzhakipov @Sibers 2012
  • 2. Plan ● introduction ● fundamentals ● solutions via WeakReference, SoftReference, etc ● analyze tools
  • 3. Memory Usage 8 primitive data types: Integers: ● byte ● short - 2 bytes ● int - 4 bytes ● long - 8 bytes Floating-point number: ● float 4 bytes ● double 8 bytes Characters: ● char - 2 bytes (utf16) Boolean ● boolean - 1 byte (1 byte versus 1 bit, alternative BitSet)
  • 4. Memory Usage Object Shallow size = object header + object fields Object header: ● Hash Code ● Garbage Collection Information ● Type Information Block Pointer ● Lock ● ArrayLength object header size: * 32bit - 8 bytes * 64bit - 16 bytes
  • 5. Memory Usage 1. public final class String { //8 bytes 2. private char value[]; // 4 bytes 3. private int offset; // 4bytes 4. private int count; //4 bytes 5. private int hash; //4 bytes 6. } 7. 8. // Shallow size of a String = 24 bytes 9. // Davlik VM for ARM 10. 11. * 32 bit architecture
  • 6. Memory Usage new String() // 24 bytes new String("a") // 40 bytes new char[1] Object Header: 12 bytes Data type char: 2 bytes Offset : 2 bytes Total: 16 bytes new String("a") == 40 bytes * 32 bit architecture * 64 bit architecture = 40+16=56bytes
  • 7. GC
  • 9. GC 1. for(int z=0; z < 10000; z++){ 2. SomeClass a = new SomeClass(); 3. a.doSomething(); 4. for(int i=0; i<100;i++; i++){ 5. StringBuilder str = new StringBuilder(); 6. str.append("This is #"); 7. str.append(i); 8. System.out.println(str.toString()); 9. } 10. } 11. ....... 12. // collects objects by gc
  • 10. Memory Leak 1. // example #1 2. ArrayList least = new ArrayList(); 3. for(int i=0; i<10000; i++){ 4. String n = "something"; // couldn't be destroyed by gc 5. least.add(n); 6. } ....* least is property of object 7. //example #2 8. @Override 9. protected void onCreate(Bundle state) { 10. super.onCreate(state); 11. 12. TextView label = new TextView(this); 13. label.setText("Leaks are bad"); 14. 15. setContentView(label); 16. }
  • 11. Memory Leak // strong reference
  • 14. SoftReference 1. SoftReference<List<Foo>> ref = new SoftReference<List<Foo>> (new LinkedList<Foo>()); // create some Foos, probably in a loop 2. List<Foo> list = ref.get(); 3. if (list == null) throw new RuntimeException("ran out of memory"); 4. list.add(foo);
  • 15. WeakReference 1. WeakReference<List<Foo>> ref = new WeakReference<List<Foo>> (new LinkedList<Foo>()); // create some Foos, probably in a loop 2. List<Foo> list = ref.get(); 3. if (list == null) throw new RuntimeException("ran out of memory"); 4. list.add(foo);
  • 16. PhantomReference 1. PhantomReference<List<Foo>> ref = new PhantomReference<List<Foo>>(new LinkedList<Foo>(), new ReferenceQueue<List<Foo>>()); // create some Foos, probably in a loop 2. List<Foo> list = ref.get(); // always return null
  • 17. Memory Analyze Tool JHat JProfiler Eclipse Memory Analyzer Yourkit Netbeans
  • 18. Eclipse Memory Analyzer Information available on http://eclipse.org/mat/
  • 19. Get a Heap ● jconsole ● jmap ● ddms(android)
  • 23. Path to GC Roots
  • 24. GC Roots The so-called GC (Garbage Collector) roots are objects special for garbage collector. Garbage collector collects those objects that are not GC roots and are not accessible by references from GC roots. There are several kinds of GC roots. One object can belong to more than one kind of root. The root kinds are: ● Class - loaded class. Classes can hold objects via static fields. ● Alive Threads ● Stack Local - local variable or parameter of method. ● Finalizer Queue Entry - object scheduled for finalization. ● GC Handle - provides a means for accessing a managed object from unmanaged memory. ● Other - objects hold from garbage collection by CLR for other reasons.
  • 26. ?
  • 27. Thanks for your time! Sources: d.android.com habrahabr.ru eclipse.org/mat