SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
1
● Jan Kotek
– jan@kotek.net
– @JanKotek
– MapDB author (database engine)
– Java developer for past 12 years
– Last 3 years independent consultant for MapDB
● Slides and code at
– https://github.com/jankotek/talk-save-java-memory
Intro
2
Intro
● This talk is about:
– Reducing memory footprint
– Object overhead
– Primitive variables and arrays
– Alternative Java Collections
● Not about:
– Garbage Collection
– Off-heap
– Performance
– Memory leaks
3
Measure memory consumption
● Runtime.getRuntime().freeMemory() difference
● Allocate until OutOfMemoryError
● Profiler
● Class or heap dump analyze such as Java Object Layout
4
Runtime.getRuntime().freeMemory()
● Get allocated memory stats
● Create new objects
● Call GC many times
● Get allocated memory difference
● Not very precise, but easy
● May not always work,
some JVMs ignore System.gc()
NanoBench nanoBench = NanoBench.create();
nanoBench.memoryOnly().warmUps(2).measurements(10)
.measure(String.format("Measure memory for %d keys", i),
new Runnable() {
@Override public void run() {
Random setRandom = new Random(4532);
ref = new HashSet<Integer>(cnt);
w hile (ref.size() < cnt) {
ref.add(setRandom.nextInt());
}
}
});
nanoBench.getMemoryBytes()
5
OutOfMemoryError
● Memory limit (-Xmx1G)
● Add entries to array in loop
● Print number of items
● JVM eventually crashes
try{
//add new entry in loop
while(true)
array[arrayPos++] = new HashMap();
}catch(OutOfMemoryError e){
memoryConsumption =
Runtime.getRuntime().maxMemory()
/ counter;
return;
}
6
Profiler
● Shows memory consumed
by single class
– (byte[], Object[])
● VisualVM is easy to use
● Flight Recorder is best
– Free outside production env.
7
Java Object Layout
● Command line tool to analyze memory layout (and space usage)
● Most advanced
● http://openjdk.java.net/projects/code-tools/jol/
● Written by Aleksey Shipilev
● Example:
$ java -jar jol-cli/target/jol-cli.jar internals java.util.HashMap
Instance size: 48 bytes (reported by Instrumentation API)
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
8
Instance overhead in Java
● Pointer overhead
– 4 to 8 bytes
– depends on JVM and amount of memory
– 64bit JVM 8 uses compressed pointer when possible
● Class info and object header
– 12 bytes
● Object alligment padding
– Between 0 and 15
35 bytes worst case scenario
9
java.lang.Integer overhead
● One object + one reference
● Total overhead 16 bytes +
reference (4 to 8 bytes)
JOL output for java.lang.Integer
OFFSET SIZE TYPE DESC
0 12 (object header)
12 4 int Integer.value
total size: 16 bytes
10
java.lang.String overhead
● Two objects and two references
● One int field (String.hash)
● Two bytes per char (UTF16)
● Other problems:
– Weak hash (many collisions)
– Defensive char[] copies
– Substring create copies etc..
JOL output for java.lang.String
OFFSET SIZE TYPE DESC
0 4 (object header)
4 4 (object header)
8 4 (object header)
12 4 char[] String.value
16 4 int String.hash
20 4 (alignment loss)
total size: 24 bytes
11
String.intern()
●
Reduces number of instances
● Each string creates new weak ref (huge GC overhead)
● Long.valueOf(11) is similar
name.toLowerCase().intern()
==
name.toLowerCase().intern()
12
Represent String as char[]
● Field is char[] or byte[]
● Get/set takes string
● GC overhead, but short lived
objects are fast to collect
● Reduced memory with many
objects (large Maps etc)
public class Person{
private char[] name;
public String getName(){
return new String(name);
}
public void setName(String name){
this.name = name.toCharArray();
}
}
13
char[] as key in Map
● char[] has no equals() and hashCode() methods
●
TreeMap key can use Comparator<char[]>
– com.google.common.primitives.Chars.lexicographicalComparator()
● java.util.HashMap can not change hash strategy
– Object2ObjectOpenCustomHashMap from FastUtil has Hash Strategies
– String.hashCode() is broken, many collisions
● Part of spec, can not be changed :-(
● ConcurrentHashMap Java8 has sorted lists to handle hash duplicates :-)
14
char[] as value in Map
● Works (mostly)
● Concurrent Compare-And-Swap operations broken
– char[].equals() uses identity
– ConcurrentMap.replace(K key, V oldValue, V newValue);
– MapDB Maps allow custom equality
15
Bitwise
class Address{
String street;
int houseNumber;
}
● Replace street with number from dictionary
●
Combine streetId and houseNumber into single long number
– 5 bytes for streetId, 3 bytes for house number and flags
● Adress become primitive number, no objects or references
16
Primitive key / value in collections
● HashMap<Long,Long> uses Object[] for keys and values
● ~40 bytes overhead for each key-value pair
● Use long[] or int[] instead
● Data locality → CPU cache friendly
– Binary search much faster
– Faster fetch of values
● Almost zero Garbage Collection
– entire HashMap uses two objects
– No objects allocated for new key or value
17
FastUtil
● http://fastutil.di.unimi.it/
● Autogenerated classes with
primitive keys and values
● Int2IntMap, Int2BooleanMap, Int2ObjectMap<V> ….
● Many classes, 17MB jar
18
FastUtil
// create new map
Int2ObjectMap<String> map =
new Int2ObjectOpenHashMap();
// put/get has primitive arg, no unboxing!
map.put(1, "aa");
map.get(1);
// also implements full mapdb interface
Map<Integer, String> map2 = map;
● Parallel interface hierarchy
● Get / set has primitive arg
version, no unboxing!
● Implements Map interface
19
Chronicle Map
● ConcurrentHashMap
● Keys and values are serialized
outside heap
● Supports any serializable data
type
● No objects or references on
heap, memory efficient
● http://chronicle.software/product
s/chronicle-map/
Map<Long, long[]> graph =
ChronicleMap
.of(Long.class, long[].class)
.entries(1_000_000_000L)
.averageValue(new long[150])
.create();
20
Conclusion
● Avoid too many object instances in long lived objects
● Short lived objects are fine, when traded for smaller memory
● Email: jan@kotek.net
● Slides and code at
– https://github.com/jankotek/talk-save-java-memory

Mais conteúdo relacionado

Mais procurados

Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0Cloudera, Inc.
 
Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Rohit Agrawal
 
Introduction to MapReduce and Hadoop
Introduction to MapReduce and HadoopIntroduction to MapReduce and Hadoop
Introduction to MapReduce and HadoopMohamed Elsaka
 
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014Julien Le Dem
 
Precog & MongoDB User Group: Skyrocket Your Analytics
Precog & MongoDB User Group: Skyrocket Your Analytics Precog & MongoDB User Group: Skyrocket Your Analytics
Precog & MongoDB User Group: Skyrocket Your Analytics MongoDB
 
GBM in H2O with Cliff Click: H2O API
GBM in H2O with Cliff Click: H2O APIGBM in H2O with Cliff Click: H2O API
GBM in H2O with Cliff Click: H2O APISri Ambati
 
On Beyond (PostgreSQL) Data Types
On Beyond (PostgreSQL) Data TypesOn Beyond (PostgreSQL) Data Types
On Beyond (PostgreSQL) Data TypesJonathan Katz
 
BDAS Shark study report 03 v1.1
BDAS Shark study report  03 v1.1BDAS Shark study report  03 v1.1
BDAS Shark study report 03 v1.1Stefanie Zhao
 
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...MongoDB
 
Mapreduce Algorithms
Mapreduce AlgorithmsMapreduce Algorithms
Mapreduce AlgorithmsAmund Tveit
 
Modern software design in Big data era
Modern software design in Big data eraModern software design in Big data era
Modern software design in Big data eraBill GU
 
Optimization Techniques
Optimization TechniquesOptimization Techniques
Optimization TechniquesJoud Khattab
 
How to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analyticsHow to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analyticsJulien Le Dem
 
Js info vis_toolkit
Js info vis_toolkitJs info vis_toolkit
Js info vis_toolkitnikhilyagnic
 
IOT with PostgreSQL
IOT with PostgreSQLIOT with PostgreSQL
IOT with PostgreSQLEDB
 
Introduction to Hadoop and MapReduce
Introduction to Hadoop and MapReduceIntroduction to Hadoop and MapReduce
Introduction to Hadoop and MapReduceDr Ganesh Iyer
 
Cliff Click Explains GBM at Netflix October 10 2013
Cliff Click Explains GBM at Netflix October 10 2013Cliff Click Explains GBM at Netflix October 10 2013
Cliff Click Explains GBM at Netflix October 10 2013Sri Ambati
 
Fosdem2017 Scientific computing on Jruby
Fosdem2017  Scientific computing on JrubyFosdem2017  Scientific computing on Jruby
Fosdem2017 Scientific computing on JrubyPrasun Anand
 
Map reduce: beyond word count
Map reduce: beyond word countMap reduce: beyond word count
Map reduce: beyond word countJeff Patti
 

Mais procurados (20)

Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0
 
Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3Hadoop MapReduce framework - Module 3
Hadoop MapReduce framework - Module 3
 
Introduction to MapReduce and Hadoop
Introduction to MapReduce and HadoopIntroduction to MapReduce and Hadoop
Introduction to MapReduce and Hadoop
 
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
 
Precog & MongoDB User Group: Skyrocket Your Analytics
Precog & MongoDB User Group: Skyrocket Your Analytics Precog & MongoDB User Group: Skyrocket Your Analytics
Precog & MongoDB User Group: Skyrocket Your Analytics
 
GBM in H2O with Cliff Click: H2O API
GBM in H2O with Cliff Click: H2O APIGBM in H2O with Cliff Click: H2O API
GBM in H2O with Cliff Click: H2O API
 
On Beyond (PostgreSQL) Data Types
On Beyond (PostgreSQL) Data TypesOn Beyond (PostgreSQL) Data Types
On Beyond (PostgreSQL) Data Types
 
BDAS Shark study report 03 v1.1
BDAS Shark study report  03 v1.1BDAS Shark study report  03 v1.1
BDAS Shark study report 03 v1.1
 
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
 
Mapreduce Algorithms
Mapreduce AlgorithmsMapreduce Algorithms
Mapreduce Algorithms
 
Modern software design in Big data era
Modern software design in Big data eraModern software design in Big data era
Modern software design in Big data era
 
Optimization Techniques
Optimization TechniquesOptimization Techniques
Optimization Techniques
 
MATLAB, netCDF, and OPeNDAP
MATLAB, netCDF, and OPeNDAPMATLAB, netCDF, and OPeNDAP
MATLAB, netCDF, and OPeNDAP
 
How to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analyticsHow to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analytics
 
Js info vis_toolkit
Js info vis_toolkitJs info vis_toolkit
Js info vis_toolkit
 
IOT with PostgreSQL
IOT with PostgreSQLIOT with PostgreSQL
IOT with PostgreSQL
 
Introduction to Hadoop and MapReduce
Introduction to Hadoop and MapReduceIntroduction to Hadoop and MapReduce
Introduction to Hadoop and MapReduce
 
Cliff Click Explains GBM at Netflix October 10 2013
Cliff Click Explains GBM at Netflix October 10 2013Cliff Click Explains GBM at Netflix October 10 2013
Cliff Click Explains GBM at Netflix October 10 2013
 
Fosdem2017 Scientific computing on Jruby
Fosdem2017  Scientific computing on JrubyFosdem2017  Scientific computing on Jruby
Fosdem2017 Scientific computing on Jruby
 
Map reduce: beyond word count
Map reduce: beyond word countMap reduce: beyond word count
Map reduce: beyond word count
 

Semelhante a Save Java memory

Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...Spark Summit
 
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
 
A super fast introduction to Spark and glance at BEAM
A super fast introduction to Spark and glance at BEAMA super fast introduction to Spark and glance at BEAM
A super fast introduction to Spark and glance at BEAMHolden Karau
 
Coding convention
Coding conventionCoding convention
Coding conventionKhoa Nguyen
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Åsa Pehrsson
 
A fast introduction to PySpark with a quick look at Arrow based UDFs
A fast introduction to PySpark with a quick look at Arrow based UDFsA fast introduction to PySpark with a quick look at Arrow based UDFs
A fast introduction to PySpark with a quick look at Arrow based UDFsHolden Karau
 
Decima Engine: Visibility in Horizon Zero Dawn
Decima Engine: Visibility in Horizon Zero DawnDecima Engine: Visibility in Horizon Zero Dawn
Decima Engine: Visibility in Horizon Zero DawnGuerrilla
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimizationguest3eed30
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory OptimizationWei Lin
 
Apache Spark™ is a multi-language engine for executing data-S5.ppt
Apache Spark™ is a multi-language engine for executing data-S5.pptApache Spark™ is a multi-language engine for executing data-S5.ppt
Apache Spark™ is a multi-language engine for executing data-S5.pptbhargavi804095
 
Sorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at SpotifySorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at SpotifyNeville Li
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScriptJorg Janke
 
Dive into spark2
Dive into spark2Dive into spark2
Dive into spark2Gal Marder
 
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
 
Cassandra Explained
Cassandra ExplainedCassandra Explained
Cassandra ExplainedEric Evans
 
Python VS GO
Python VS GOPython VS GO
Python VS GOOfir Nir
 

Semelhante a Save Java memory (20)

Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
 
Memory management
Memory managementMemory management
Memory management
 
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)
 
Java Memory Analysis: Problems and Solutions
Java Memory Analysis: Problems and SolutionsJava Memory Analysis: Problems and Solutions
Java Memory Analysis: Problems and Solutions
 
A super fast introduction to Spark and glance at BEAM
A super fast introduction to Spark and glance at BEAMA super fast introduction to Spark and glance at BEAM
A super fast introduction to Spark and glance at BEAM
 
Coding convention
Coding conventionCoding convention
Coding convention
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11
 
A fast introduction to PySpark with a quick look at Arrow based UDFs
A fast introduction to PySpark with a quick look at Arrow based UDFsA fast introduction to PySpark with a quick look at Arrow based UDFs
A fast introduction to PySpark with a quick look at Arrow based UDFs
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Decima Engine: Visibility in Horizon Zero Dawn
Decima Engine: Visibility in Horizon Zero DawnDecima Engine: Visibility in Horizon Zero Dawn
Decima Engine: Visibility in Horizon Zero Dawn
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
 
Memory Optimization
Memory OptimizationMemory Optimization
Memory Optimization
 
Apache Spark™ is a multi-language engine for executing data-S5.ppt
Apache Spark™ is a multi-language engine for executing data-S5.pptApache Spark™ is a multi-language engine for executing data-S5.ppt
Apache Spark™ is a multi-language engine for executing data-S5.ppt
 
Sorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at SpotifySorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at Spotify
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScript
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
Dive into spark2
Dive into spark2Dive into spark2
Dive into spark2
 
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
 
Cassandra Explained
Cassandra ExplainedCassandra Explained
Cassandra Explained
 
Python VS GO
Python VS GOPython VS GO
Python VS GO
 

Mais de JavaDayUA

STEMing Kids: One workshop at a time
STEMing Kids: One workshop at a timeSTEMing Kids: One workshop at a time
STEMing Kids: One workshop at a timeJavaDayUA
 
Flavors of Concurrency in Java
Flavors of Concurrency in JavaFlavors of Concurrency in Java
Flavors of Concurrency in JavaJavaDayUA
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9JavaDayUA
 
Continuously building, releasing and deploying software: The Revenge of the M...
Continuously building, releasing and deploying software: The Revenge of the M...Continuously building, releasing and deploying software: The Revenge of the M...
Continuously building, releasing and deploying software: The Revenge of the M...JavaDayUA
 
The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
The Epic Groovy Puzzlers S02: The Revenge of the ParenthesesThe Epic Groovy Puzzlers S02: The Revenge of the Parentheses
The Epic Groovy Puzzlers S02: The Revenge of the ParenthesesJavaDayUA
 
20 Years of Java
20 Years of Java20 Years of Java
20 Years of JavaJavaDayUA
 
How to get the most out of code reviews
How to get the most out of code reviewsHow to get the most out of code reviews
How to get the most out of code reviewsJavaDayUA
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8JavaDayUA
 
Virtual Private Cloud with container technologies for DevOps
Virtual Private Cloud with container technologies for DevOpsVirtual Private Cloud with container technologies for DevOps
Virtual Private Cloud with container technologies for DevOpsJavaDayUA
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJavaDayUA
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureJavaDayUA
 
Design rationales in the JRockit JVM
Design rationales in the JRockit JVMDesign rationales in the JRockit JVM
Design rationales in the JRockit JVMJavaDayUA
 
Next-gen DevOps engineering with Docker and Kubernetes by Antons Kranga
Next-gen DevOps engineering with Docker and Kubernetes by Antons KrangaNext-gen DevOps engineering with Docker and Kubernetes by Antons Kranga
Next-gen DevOps engineering with Docker and Kubernetes by Antons KrangaJavaDayUA
 
Apache Cassandra. Inception - all you need to know by Mikhail Dubkov
Apache Cassandra. Inception - all you need to know by Mikhail DubkovApache Cassandra. Inception - all you need to know by Mikhail Dubkov
Apache Cassandra. Inception - all you need to know by Mikhail DubkovJavaDayUA
 
Solution Architecture tips & tricks by Roman Shramkov
Solution Architecture tips & tricks by Roman ShramkovSolution Architecture tips & tricks by Roman Shramkov
Solution Architecture tips & tricks by Roman ShramkovJavaDayUA
 
Testing in Legacy: from Rags to Riches by Taras Slipets
Testing in Legacy: from Rags to Riches by Taras SlipetsTesting in Legacy: from Rags to Riches by Taras Slipets
Testing in Legacy: from Rags to Riches by Taras SlipetsJavaDayUA
 
Reactive programming and Hystrix fault tolerance by Max Myslyvtsev
Reactive programming and Hystrix fault tolerance by Max MyslyvtsevReactive programming and Hystrix fault tolerance by Max Myslyvtsev
Reactive programming and Hystrix fault tolerance by Max MyslyvtsevJavaDayUA
 
Spark-driven audience counting by Boris Trofimov
Spark-driven audience counting by Boris TrofimovSpark-driven audience counting by Boris Trofimov
Spark-driven audience counting by Boris TrofimovJavaDayUA
 
API first with Swagger and Scala by Slava Schmidt
API first with Swagger and Scala by  Slava SchmidtAPI first with Swagger and Scala by  Slava Schmidt
API first with Swagger and Scala by Slava SchmidtJavaDayUA
 
JavaFX 8 everywhere; write once run anywhere by Mohamed Taman
JavaFX 8 everywhere; write once run anywhere by Mohamed TamanJavaFX 8 everywhere; write once run anywhere by Mohamed Taman
JavaFX 8 everywhere; write once run anywhere by Mohamed TamanJavaDayUA
 

Mais de JavaDayUA (20)

STEMing Kids: One workshop at a time
STEMing Kids: One workshop at a timeSTEMing Kids: One workshop at a time
STEMing Kids: One workshop at a time
 
Flavors of Concurrency in Java
Flavors of Concurrency in JavaFlavors of Concurrency in Java
Flavors of Concurrency in Java
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
 
Continuously building, releasing and deploying software: The Revenge of the M...
Continuously building, releasing and deploying software: The Revenge of the M...Continuously building, releasing and deploying software: The Revenge of the M...
Continuously building, releasing and deploying software: The Revenge of the M...
 
The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
The Epic Groovy Puzzlers S02: The Revenge of the ParenthesesThe Epic Groovy Puzzlers S02: The Revenge of the Parentheses
The Epic Groovy Puzzlers S02: The Revenge of the Parentheses
 
20 Years of Java
20 Years of Java20 Years of Java
20 Years of Java
 
How to get the most out of code reviews
How to get the most out of code reviewsHow to get the most out of code reviews
How to get the most out of code reviews
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8
 
Virtual Private Cloud with container technologies for DevOps
Virtual Private Cloud with container technologies for DevOpsVirtual Private Cloud with container technologies for DevOps
Virtual Private Cloud with container technologies for DevOps
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java Platform
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and Architecture
 
Design rationales in the JRockit JVM
Design rationales in the JRockit JVMDesign rationales in the JRockit JVM
Design rationales in the JRockit JVM
 
Next-gen DevOps engineering with Docker and Kubernetes by Antons Kranga
Next-gen DevOps engineering with Docker and Kubernetes by Antons KrangaNext-gen DevOps engineering with Docker and Kubernetes by Antons Kranga
Next-gen DevOps engineering with Docker and Kubernetes by Antons Kranga
 
Apache Cassandra. Inception - all you need to know by Mikhail Dubkov
Apache Cassandra. Inception - all you need to know by Mikhail DubkovApache Cassandra. Inception - all you need to know by Mikhail Dubkov
Apache Cassandra. Inception - all you need to know by Mikhail Dubkov
 
Solution Architecture tips & tricks by Roman Shramkov
Solution Architecture tips & tricks by Roman ShramkovSolution Architecture tips & tricks by Roman Shramkov
Solution Architecture tips & tricks by Roman Shramkov
 
Testing in Legacy: from Rags to Riches by Taras Slipets
Testing in Legacy: from Rags to Riches by Taras SlipetsTesting in Legacy: from Rags to Riches by Taras Slipets
Testing in Legacy: from Rags to Riches by Taras Slipets
 
Reactive programming and Hystrix fault tolerance by Max Myslyvtsev
Reactive programming and Hystrix fault tolerance by Max MyslyvtsevReactive programming and Hystrix fault tolerance by Max Myslyvtsev
Reactive programming and Hystrix fault tolerance by Max Myslyvtsev
 
Spark-driven audience counting by Boris Trofimov
Spark-driven audience counting by Boris TrofimovSpark-driven audience counting by Boris Trofimov
Spark-driven audience counting by Boris Trofimov
 
API first with Swagger and Scala by Slava Schmidt
API first with Swagger and Scala by  Slava SchmidtAPI first with Swagger and Scala by  Slava Schmidt
API first with Swagger and Scala by Slava Schmidt
 
JavaFX 8 everywhere; write once run anywhere by Mohamed Taman
JavaFX 8 everywhere; write once run anywhere by Mohamed TamanJavaFX 8 everywhere; write once run anywhere by Mohamed Taman
JavaFX 8 everywhere; write once run anywhere by Mohamed Taman
 

Último

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
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
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 

Último (20)

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
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
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
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...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
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...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 

Save Java memory

  • 1. 1 ● Jan Kotek – jan@kotek.net – @JanKotek – MapDB author (database engine) – Java developer for past 12 years – Last 3 years independent consultant for MapDB ● Slides and code at – https://github.com/jankotek/talk-save-java-memory Intro
  • 2. 2 Intro ● This talk is about: – Reducing memory footprint – Object overhead – Primitive variables and arrays – Alternative Java Collections ● Not about: – Garbage Collection – Off-heap – Performance – Memory leaks
  • 3. 3 Measure memory consumption ● Runtime.getRuntime().freeMemory() difference ● Allocate until OutOfMemoryError ● Profiler ● Class or heap dump analyze such as Java Object Layout
  • 4. 4 Runtime.getRuntime().freeMemory() ● Get allocated memory stats ● Create new objects ● Call GC many times ● Get allocated memory difference ● Not very precise, but easy ● May not always work, some JVMs ignore System.gc() NanoBench nanoBench = NanoBench.create(); nanoBench.memoryOnly().warmUps(2).measurements(10) .measure(String.format("Measure memory for %d keys", i), new Runnable() { @Override public void run() { Random setRandom = new Random(4532); ref = new HashSet<Integer>(cnt); w hile (ref.size() < cnt) { ref.add(setRandom.nextInt()); } } }); nanoBench.getMemoryBytes()
  • 5. 5 OutOfMemoryError ● Memory limit (-Xmx1G) ● Add entries to array in loop ● Print number of items ● JVM eventually crashes try{ //add new entry in loop while(true) array[arrayPos++] = new HashMap(); }catch(OutOfMemoryError e){ memoryConsumption = Runtime.getRuntime().maxMemory() / counter; return; }
  • 6. 6 Profiler ● Shows memory consumed by single class – (byte[], Object[]) ● VisualVM is easy to use ● Flight Recorder is best – Free outside production env.
  • 7. 7 Java Object Layout ● Command line tool to analyze memory layout (and space usage) ● Most advanced ● http://openjdk.java.net/projects/code-tools/jol/ ● Written by Aleksey Shipilev ● Example: $ java -jar jol-cli/target/jol-cli.jar internals java.util.HashMap Instance size: 48 bytes (reported by Instrumentation API) Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
  • 8. 8 Instance overhead in Java ● Pointer overhead – 4 to 8 bytes – depends on JVM and amount of memory – 64bit JVM 8 uses compressed pointer when possible ● Class info and object header – 12 bytes ● Object alligment padding – Between 0 and 15 35 bytes worst case scenario
  • 9. 9 java.lang.Integer overhead ● One object + one reference ● Total overhead 16 bytes + reference (4 to 8 bytes) JOL output for java.lang.Integer OFFSET SIZE TYPE DESC 0 12 (object header) 12 4 int Integer.value total size: 16 bytes
  • 10. 10 java.lang.String overhead ● Two objects and two references ● One int field (String.hash) ● Two bytes per char (UTF16) ● Other problems: – Weak hash (many collisions) – Defensive char[] copies – Substring create copies etc.. JOL output for java.lang.String OFFSET SIZE TYPE DESC 0 4 (object header) 4 4 (object header) 8 4 (object header) 12 4 char[] String.value 16 4 int String.hash 20 4 (alignment loss) total size: 24 bytes
  • 11. 11 String.intern() ● Reduces number of instances ● Each string creates new weak ref (huge GC overhead) ● Long.valueOf(11) is similar name.toLowerCase().intern() == name.toLowerCase().intern()
  • 12. 12 Represent String as char[] ● Field is char[] or byte[] ● Get/set takes string ● GC overhead, but short lived objects are fast to collect ● Reduced memory with many objects (large Maps etc) public class Person{ private char[] name; public String getName(){ return new String(name); } public void setName(String name){ this.name = name.toCharArray(); } }
  • 13. 13 char[] as key in Map ● char[] has no equals() and hashCode() methods ● TreeMap key can use Comparator<char[]> – com.google.common.primitives.Chars.lexicographicalComparator() ● java.util.HashMap can not change hash strategy – Object2ObjectOpenCustomHashMap from FastUtil has Hash Strategies – String.hashCode() is broken, many collisions ● Part of spec, can not be changed :-( ● ConcurrentHashMap Java8 has sorted lists to handle hash duplicates :-)
  • 14. 14 char[] as value in Map ● Works (mostly) ● Concurrent Compare-And-Swap operations broken – char[].equals() uses identity – ConcurrentMap.replace(K key, V oldValue, V newValue); – MapDB Maps allow custom equality
  • 15. 15 Bitwise class Address{ String street; int houseNumber; } ● Replace street with number from dictionary ● Combine streetId and houseNumber into single long number – 5 bytes for streetId, 3 bytes for house number and flags ● Adress become primitive number, no objects or references
  • 16. 16 Primitive key / value in collections ● HashMap<Long,Long> uses Object[] for keys and values ● ~40 bytes overhead for each key-value pair ● Use long[] or int[] instead ● Data locality → CPU cache friendly – Binary search much faster – Faster fetch of values ● Almost zero Garbage Collection – entire HashMap uses two objects – No objects allocated for new key or value
  • 17. 17 FastUtil ● http://fastutil.di.unimi.it/ ● Autogenerated classes with primitive keys and values ● Int2IntMap, Int2BooleanMap, Int2ObjectMap<V> …. ● Many classes, 17MB jar
  • 18. 18 FastUtil // create new map Int2ObjectMap<String> map = new Int2ObjectOpenHashMap(); // put/get has primitive arg, no unboxing! map.put(1, "aa"); map.get(1); // also implements full mapdb interface Map<Integer, String> map2 = map; ● Parallel interface hierarchy ● Get / set has primitive arg version, no unboxing! ● Implements Map interface
  • 19. 19 Chronicle Map ● ConcurrentHashMap ● Keys and values are serialized outside heap ● Supports any serializable data type ● No objects or references on heap, memory efficient ● http://chronicle.software/product s/chronicle-map/ Map<Long, long[]> graph = ChronicleMap .of(Long.class, long[].class) .entries(1_000_000_000L) .averageValue(new long[150]) .create();
  • 20. 20 Conclusion ● Avoid too many object instances in long lived objects ● Short lived objects are fine, when traded for smaller memory ● Email: jan@kotek.net ● Slides and code at – https://github.com/jankotek/talk-save-java-memory