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?

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 javacAnna Brzezińska
 
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 SechetAndrei Alexandrescu
 
TDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirTDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirWix Engineering
 
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 storeRedis Labs
 
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 profitAlex Matrosov
 
Active records before_type_cast
Active records before_type_castActive records before_type_cast
Active records before_type_castthehoagie
 
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)Kai Chan
 
Coding using jscript test complete
Coding using jscript test completeCoding using jscript test complete
Coding using jscript test completeViresh Doshi
 
Ts archiving
Ts   archivingTs   archiving
Ts archivingConfiz
 
Using spark data frame for sql
Using spark data frame for sqlUsing spark data frame for sql
Using spark data frame for sqlDaeMyung Kang
 
HexRaysCodeXplorer: make object-oriented RE easier
HexRaysCodeXplorer: make object-oriented RE easierHexRaysCodeXplorer: make object-oriented RE easier
HexRaysCodeXplorer: make object-oriented RE easierAlex Matrosov
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetJava JVM Memory Cheat Sheet
Java JVM Memory Cheat SheetMark Papis
 

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: Fundamentals, Leaks, and Tools

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 kernelVitaly Nikolenko
 
Save Java memory
Save Java memorySave Java memory
Save Java memoryJavaDayUA
 
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_gtugketan_patel25
 
Php Extensions for Dummies
Php Extensions for DummiesPhp Extensions for Dummies
Php Extensions for DummiesElizabeth Smith
 
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 FirestarterMithun T. Dhar
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory OptimizationWei Lin
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimizationguest3eed30
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
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 FranceDavid Delabassee
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)JiandSon
 
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)Dina Goldshtein
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
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.pptxpetabridge
 
Kerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit eastKerberizing spark. Spark Summit east
Kerberizing spark. Spark Summit eastJorge Lopez-Malla
 
How to write memory efficient code?
How to write memory efficient code?How to write memory efficient code?
How to write memory efficient code?Tier1 app
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applicationsjeromevdl
 
Drupal MySQL Cluster
Drupal MySQL ClusterDrupal MySQL Cluster
Drupal MySQL ClusterKris Buytaert
 

Ähnlich wie Memory Management: Fundamentals, Leaks, and Tools (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

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 

Memory Management: Fundamentals, Leaks, and Tools

  • 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