SlideShare uma empresa Scribd logo
1 de 40
Why learn internals?
By: Shaul Rosenzweig
Part 1: collection hell
Bit on ArrayList, StringBuilder, etc
● Backed by Java array
● Constructor allocates initial 4-16 bytes (depends on implementation)
● When it is filled, it doubles array size and copies the memory
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b b , _
a b c
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e , _
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e , _ f g h
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e , _ f g h , _
StringBuilder sb = new StringBuilder();
for(FooObj obj : fooList) {
if(sb.length() > 0) sb.append(", ");
sb.append(obj.getData());
}
a b c , _ d e , _ f g h , _
o
a b c , _ d e , _ f g h , _ m n
Copy and GC
OkHttp old disk cache code, called by Picasso
for (int x = 0; x < valueCount; x++) {
cleanFiles[x] = new File(directory, key + "." + x);
dirtyFiles[x] = new File(directory, key + "." + x + ".tmp");
}
What really happens...
for (int x = 0; x < valueCount; x++) {
StringBuilder b1 = new StringBuilder();
b1.append(key);
b1.append(".");
b1.append(x);
cleanFiles[x] = new File(directory, b1.toString());
StringBuilder b2 = new StringBuilder();
b2.append(key);
b2.append(".");
b2.append(x);
b2.append(".tmp");
dirtyFiles[x] = new File(directory, b2.toString());
}
Optimized code
StringBuilder b = new StringBuilder(key);
b.append(".");
int truncateTo = b.length();
for (int x = 0; x < valueCount; x++) {
b.append(x);
cleanFiles[x] = new File(directory, b.toString());
b.append(".tmp");
dirtyFiles[x] = new File(directory, b.toString());
b.setLength(truncateTo);
}
Part 2: multidex hell
How many methods? 0?
class MyClass {
}
How many methods? 1?
$ javac MyClass.java
$ javap MyClass.class
Class MyClass {
MyClass();
}
How many methods? 2?
$ dx --dex --output=myclass.dex
MyClass.class
$ dexdump -f myclass.dex
method_ids_size : 2
$ dex-method-list myclass.dex
MyClass <init>()
java.lang.Object <init>()
Inner classes
public class Outer {
private static String getStatic(String name) {
return "Hello " + name;
}
private class Inner {
void doSomething(OtherObj other, String name)
{
other.setGreeting(Outer.getStatic(name));
}
Inner classes do not exist, extra method
$ javac Outer.java
$ ls
Outer.class
Outer.java
Outer$Inner.class
$ javap -p Outer.class
class Outer {
Outer();
private static java.lang.String displayText(…);
static java.lang.String access$000(…);
}
What javac did? This code does the same
public class Outer {
private static String getStatic(String name) {
return "Hello " + name;
}
}
private class Outer$Inner {
void doSomething(OtherObj other, String name) {
other.setGreeting(Outer.getStatic(name));
}
}
WTF is this access$000 method?
$ javap -p -c Outer
class Outer{
...
static java.lang.String access$000(…);
Code:
0: aload_0
1: invokestatic #1 // Method getStatic:…
4: areturn
}
Accessor method bomb
class AccessorMethodBomb{
private int count;
private Inner inner;
@Override protected void doSomething(Bundle state) {
inner = new Inner() {
@Override public void blah() {
count = 0;
++count;
--count;
count++;
count--;
...
6 accessors and 2 constructors added
class AccessorMethodBomb {
AccessorMethodBomb();
Object();
protected void doSomething();
static int access$002(AccessorMethodBomb, int); // count = 0 write
static int access$004(AccessorMethodBomb); // ++count preinc
static int access$006(AccessorMethodBomb); // --count predec
static int access$008(AccessorMethodBomb); // count++ postinc
static int access$010(AccessorMethodBomb); // count-- postdec
static int access$000(AccessorMethodBomb); // count read
}
Common problem
● Inner classes added to compiler in Java 1.1 with accessor method trick
○ VM is not inner class aware
○ Quick and dirty addition: inner class is really a separate class
○ If there is no access, accessor method is added by javac
● Optimizers do not solve this problem
● Common problem: Facebook app has 5000 avoidable accessor methods
● Similar situation in most 3rd party libs and apps
● Slows down method lookup
● Triggers need for multidex much sooner than needed
Part 3: GC compactor
Moving garbage collector
● Added in ART
● Two compaction modes:
○ Semi-space for low mem devices, Homogenous for normal
● Compacts fragmented memory
● Can’t work when process is active
● Result of it not working: fragmented memory
● Let the app rest, let the compactor compact!
Part 4: in praise of zygote
Zygote tidbits
● Zygote system service is started by init.rc as parent of all Java apps
● Loads Android framework into memory and waits on a socket
● When app runs, zygote forks, and original one runs the app
● Copy on write - framework memory is read only, so it never changes
● All apps use same Android framework code loaded in RAM
● On PC, every JVM instance loads its own copy of Java framework
● Slow start speed and big memory footprint
● Android runs Java in similar way like servers
Part 5: CPU cache is your friend
How does it influence execution speed?
int[] arr = new int[64 * 1024 * 1024];
//does 100% of work and takes measured 80ms
for (int i = 0; i < arr.Length; i++) arr[i] *= 3;
//does 6% of the work and takes measured 78ms
for (int i = 0; i < arr.Length; i += 16) arr[i] *= 3;
ARM cache architecture
ARM big.LITTLE cache architecture
CPU 1 (fast) CPU 2 (slow)
Memory reference latency
● Register reference: too fast to be measured
● L1 cache reference: 0.5 ns
● L2 cache reference: 7ns
● RAM reference: 100ns
As function of step
for (int i = 0; i < arr.Length; i += K) arr[i] *= 3;
How to minimize cache misses
● While data is being read, CPU cycles idle away
● Less read latency = less sleep cycles
● L1 cache is 200 times faster than DRAM
● Volume: 32k L1 data cache, 512k-4mb L2 cache
● L2 is shared between cores, so less mide be available
● Keep data in sequential buffers
● OOP Objects tend to scatter data in memory
● CPU reads memory in cache lines of 64 bytes
● Cache misses: bad, cache hits: good
Part 6: NAND flash endurance
NAND flash write endurance
● Stores charge behind floating gate, which degrades on writes
● TLC and MLC flash has 500-3000 write cycles
● Controller tries to spread the writes out to mitigate the effect
● When worn down, device starts getting bad sectors
● Bad sectors cause kernel to remount partition as read-only
● Application that is constantly writing to storage will wear it down
● Try to cache writes, do not flush every byte, if possible use removable
storage which can be replaced

Mais conteúdo relacionado

Mais procurados

Engineering fast indexes
Engineering fast indexesEngineering fast indexes
Engineering fast indexesDaniel Lemire
 
Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)Daniel Lemire
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopSages
 
DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright Andrei Alexandrescu
 
Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)Angel Boy
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseSages
 
RedisConf17- durable_rules
RedisConf17- durable_rulesRedisConf17- durable_rules
RedisConf17- durable_rulesRedis Labs
 
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...LogeekNightUkraine
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"OdessaJS Conf
 
NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesTeerawat Issariyakul
 
Intro to Rust from Applicative / NY Meetup
Intro to Rust from Applicative / NY MeetupIntro to Rust from Applicative / NY Meetup
Intro to Rust from Applicative / NY Meetupnikomatsakis
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorialnikomatsakis
 
Swug July 2010 - windows debugging by sainath
Swug July 2010 - windows debugging by sainathSwug July 2010 - windows debugging by sainath
Swug July 2010 - windows debugging by sainathDennis Chung
 
Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22nikomatsakis
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rustnikomatsakis
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxSoumen Santra
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! aleks-f
 

Mais procurados (20)

Engineering fast indexes
Engineering fast indexesEngineering fast indexes
Engineering fast indexes
 
Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)Engineering fast indexes (Deepdive)
Engineering fast indexes (Deepdive)
 
Protostar VM - Heap3
Protostar VM - Heap3Protostar VM - Heap3
Protostar VM - Heap3
 
#2 (UDP)
#2 (UDP)#2 (UDP)
#2 (UDP)
 
Wprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache HadoopWprowadzenie do technologi Big Data i Apache Hadoop
Wprowadzenie do technologi Big Data i Apache Hadoop
 
tokyotalk
tokyotalktokyotalk
tokyotalk
 
DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright DConf 2016: Keynote by Walter Bright
DConf 2016: Keynote by Walter Bright
 
Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
RedisConf17- durable_rules
RedisConf17- durable_rulesRedisConf17- durable_rules
RedisConf17- durable_rules
 
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
 
NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variables
 
Intro to Rust from Applicative / NY Meetup
Intro to Rust from Applicative / NY MeetupIntro to Rust from Applicative / NY Meetup
Intro to Rust from Applicative / NY Meetup
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
 
Swug July 2010 - windows debugging by sainath
Swug July 2010 - windows debugging by sainathSwug July 2010 - windows debugging by sainath
Swug July 2010 - windows debugging by sainath
 
Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with Linux
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 

Semelhante a Why learn Internals?

PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESPyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESAlessandro Molina
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centrejatin batra
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Kai Chan
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerPlatonov Sergey
 
PPU Optimisation Lesson
PPU Optimisation LessonPPU Optimisation Lesson
PPU Optimisation Lessonslantsixgames
 
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
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimizationguest3eed30
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory OptimizationWei Lin
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Linux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloudLinux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloudAndrea Righi
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugsComputer Science Club
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11Henry Schreiner
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCKernel TLV
 
Exploiting GPU's for Columnar DataFrrames by Kiran Lonikar
Exploiting GPU's for Columnar DataFrrames by Kiran LonikarExploiting GPU's for Columnar DataFrrames by Kiran Lonikar
Exploiting GPU's for Columnar DataFrrames by Kiran LonikarSpark Summit
 
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen TatarynovWorkshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen TatarynovFwdays
 
Project Tungsten: Bringing Spark Closer to Bare Metal
Project Tungsten: Bringing Spark Closer to Bare MetalProject Tungsten: Bringing Spark Closer to Bare Metal
Project Tungsten: Bringing Spark Closer to Bare MetalDatabricks
 
PythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummiesPythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummiesTatiana Al-Chueyr
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeYung-Yu Chen
 

Semelhante a Why learn Internals? (20)

PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATESPyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
PyConIT6 - MAKING SESSIONS AND CACHING ROOMMATES
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
C Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer CentreC Programming Training in Ambala ! Batra Computer Centre
C Programming Training in Ambala ! Batra Computer Centre
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)
 
Address/Thread/Memory Sanitizer
Address/Thread/Memory SanitizerAddress/Thread/Memory Sanitizer
Address/Thread/Memory Sanitizer
 
PPU Optimisation Lesson
PPU Optimisation LessonPPU Optimisation Lesson
PPU Optimisation Lesson
 
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
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Linux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloudLinux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloud
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 
Exploiting GPU's for Columnar DataFrrames by Kiran Lonikar
Exploiting GPU's for Columnar DataFrrames by Kiran LonikarExploiting GPU's for Columnar DataFrrames by Kiran Lonikar
Exploiting GPU's for Columnar DataFrrames by Kiran Lonikar
 
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen TatarynovWorkshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
 
Project Tungsten: Bringing Spark Closer to Bare Metal
Project Tungsten: Bringing Spark Closer to Bare MetalProject Tungsten: Bringing Spark Closer to Bare Metal
Project Tungsten: Bringing Spark Closer to Bare Metal
 
PythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummiesPythonBrasil[8] - CPython for dummies
PythonBrasil[8] - CPython for dummies
 
Start Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New RopeStart Wrap Episode 11: A New Rope
Start Wrap Episode 11: A New Rope
 

Mais de Shaul Rosenzwieg

Brainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a proBrainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a proShaul Rosenzwieg
 
Secure Android Development
Secure Android DevelopmentSecure Android Development
Secure Android DevelopmentShaul Rosenzwieg
 
Android virtual machine internals
Android virtual machine internalsAndroid virtual machine internals
Android virtual machine internalsShaul Rosenzwieg
 

Mais de Shaul Rosenzwieg (8)

Brainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a proBrainstorming: Manage your ideas like a pro
Brainstorming: Manage your ideas like a pro
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
 
Android Open Accessory
Android Open AccessoryAndroid Open Accessory
Android Open Accessory
 
Lifecycle of a pixel
Lifecycle of a pixelLifecycle of a pixel
Lifecycle of a pixel
 
Secure Android Development
Secure Android DevelopmentSecure Android Development
Secure Android Development
 
Android virtual machine internals
Android virtual machine internalsAndroid virtual machine internals
Android virtual machine internals
 
Binder: Android IPC
Binder: Android IPCBinder: Android IPC
Binder: Android IPC
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Último (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 

Why learn Internals?

  • 1. Why learn internals? By: Shaul Rosenzweig
  • 3. Bit on ArrayList, StringBuilder, etc ● Backed by Java array ● Constructor allocates initial 4-16 bytes (depends on implementation) ● When it is filled, it doubles array size and copies the memory StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); }
  • 4. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); }
  • 5. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); }
  • 6. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); }
  • 7. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c
  • 8. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b b , _ a b c
  • 9. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e
  • 10. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e , _
  • 11. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e , _ f g h
  • 12. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e , _ f g h , _
  • 13. StringBuilder sb = new StringBuilder(); for(FooObj obj : fooList) { if(sb.length() > 0) sb.append(", "); sb.append(obj.getData()); } a b c , _ d e , _ f g h , _ o a b c , _ d e , _ f g h , _ m n Copy and GC
  • 14. OkHttp old disk cache code, called by Picasso for (int x = 0; x < valueCount; x++) { cleanFiles[x] = new File(directory, key + "." + x); dirtyFiles[x] = new File(directory, key + "." + x + ".tmp"); }
  • 15. What really happens... for (int x = 0; x < valueCount; x++) { StringBuilder b1 = new StringBuilder(); b1.append(key); b1.append("."); b1.append(x); cleanFiles[x] = new File(directory, b1.toString()); StringBuilder b2 = new StringBuilder(); b2.append(key); b2.append("."); b2.append(x); b2.append(".tmp"); dirtyFiles[x] = new File(directory, b2.toString()); }
  • 16. Optimized code StringBuilder b = new StringBuilder(key); b.append("."); int truncateTo = b.length(); for (int x = 0; x < valueCount; x++) { b.append(x); cleanFiles[x] = new File(directory, b.toString()); b.append(".tmp"); dirtyFiles[x] = new File(directory, b.toString()); b.setLength(truncateTo); }
  • 18. How many methods? 0? class MyClass { }
  • 19. How many methods? 1? $ javac MyClass.java $ javap MyClass.class Class MyClass { MyClass(); }
  • 20. How many methods? 2? $ dx --dex --output=myclass.dex MyClass.class $ dexdump -f myclass.dex method_ids_size : 2 $ dex-method-list myclass.dex MyClass <init>() java.lang.Object <init>()
  • 21. Inner classes public class Outer { private static String getStatic(String name) { return "Hello " + name; } private class Inner { void doSomething(OtherObj other, String name) { other.setGreeting(Outer.getStatic(name)); }
  • 22. Inner classes do not exist, extra method $ javac Outer.java $ ls Outer.class Outer.java Outer$Inner.class $ javap -p Outer.class class Outer { Outer(); private static java.lang.String displayText(…); static java.lang.String access$000(…); }
  • 23. What javac did? This code does the same public class Outer { private static String getStatic(String name) { return "Hello " + name; } } private class Outer$Inner { void doSomething(OtherObj other, String name) { other.setGreeting(Outer.getStatic(name)); } }
  • 24. WTF is this access$000 method? $ javap -p -c Outer class Outer{ ... static java.lang.String access$000(…); Code: 0: aload_0 1: invokestatic #1 // Method getStatic:… 4: areturn }
  • 25. Accessor method bomb class AccessorMethodBomb{ private int count; private Inner inner; @Override protected void doSomething(Bundle state) { inner = new Inner() { @Override public void blah() { count = 0; ++count; --count; count++; count--; ...
  • 26. 6 accessors and 2 constructors added class AccessorMethodBomb { AccessorMethodBomb(); Object(); protected void doSomething(); static int access$002(AccessorMethodBomb, int); // count = 0 write static int access$004(AccessorMethodBomb); // ++count preinc static int access$006(AccessorMethodBomb); // --count predec static int access$008(AccessorMethodBomb); // count++ postinc static int access$010(AccessorMethodBomb); // count-- postdec static int access$000(AccessorMethodBomb); // count read }
  • 27. Common problem ● Inner classes added to compiler in Java 1.1 with accessor method trick ○ VM is not inner class aware ○ Quick and dirty addition: inner class is really a separate class ○ If there is no access, accessor method is added by javac ● Optimizers do not solve this problem ● Common problem: Facebook app has 5000 avoidable accessor methods ● Similar situation in most 3rd party libs and apps ● Slows down method lookup ● Triggers need for multidex much sooner than needed
  • 28. Part 3: GC compactor
  • 29. Moving garbage collector ● Added in ART ● Two compaction modes: ○ Semi-space for low mem devices, Homogenous for normal ● Compacts fragmented memory ● Can’t work when process is active ● Result of it not working: fragmented memory ● Let the app rest, let the compactor compact!
  • 30. Part 4: in praise of zygote
  • 31. Zygote tidbits ● Zygote system service is started by init.rc as parent of all Java apps ● Loads Android framework into memory and waits on a socket ● When app runs, zygote forks, and original one runs the app ● Copy on write - framework memory is read only, so it never changes ● All apps use same Android framework code loaded in RAM ● On PC, every JVM instance loads its own copy of Java framework ● Slow start speed and big memory footprint ● Android runs Java in similar way like servers
  • 32. Part 5: CPU cache is your friend
  • 33. How does it influence execution speed? int[] arr = new int[64 * 1024 * 1024]; //does 100% of work and takes measured 80ms for (int i = 0; i < arr.Length; i++) arr[i] *= 3; //does 6% of the work and takes measured 78ms for (int i = 0; i < arr.Length; i += 16) arr[i] *= 3;
  • 35. ARM big.LITTLE cache architecture CPU 1 (fast) CPU 2 (slow)
  • 36. Memory reference latency ● Register reference: too fast to be measured ● L1 cache reference: 0.5 ns ● L2 cache reference: 7ns ● RAM reference: 100ns
  • 37. As function of step for (int i = 0; i < arr.Length; i += K) arr[i] *= 3;
  • 38. How to minimize cache misses ● While data is being read, CPU cycles idle away ● Less read latency = less sleep cycles ● L1 cache is 200 times faster than DRAM ● Volume: 32k L1 data cache, 512k-4mb L2 cache ● L2 is shared between cores, so less mide be available ● Keep data in sequential buffers ● OOP Objects tend to scatter data in memory ● CPU reads memory in cache lines of 64 bytes ● Cache misses: bad, cache hits: good
  • 39. Part 6: NAND flash endurance
  • 40. NAND flash write endurance ● Stores charge behind floating gate, which degrades on writes ● TLC and MLC flash has 500-3000 write cycles ● Controller tries to spread the writes out to mitigate the effect ● When worn down, device starts getting bad sectors ● Bad sectors cause kernel to remount partition as read-only ● Application that is constantly writing to storage will wear it down ● Try to cache writes, do not flush every byte, if possible use removable storage which can be replaced