SlideShare ist ein Scribd-Unternehmen logo
1 von 27
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

Ts archiving
Ts   archivingTs   archiving
Ts archiving
Confiz
 

Was ist angesagt? (20)

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

Ähnlich wie Memory management

Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
ketan_patel25
 
Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for Dummies
Elizabeth Smith
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
guest3eed30
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
Wei Lin
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 

Ähnlich wie Memory management (20)

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

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

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
  • 8.
  • 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