SlideShare a Scribd company logo
1 of 29
Download to read offline
Forgive me for I have allocated
Tomasz Kowalczewski
Log4j2 Logger Quiz
Log4j2 Logger Quiz
How many objects does this loop create
when debug logging is disabled?
while (true) {

LOGGER.debug("{} {}", "a", "b");

}

Log4j2 Logger
while (true) {

LOGGER.debug("{} {}", "a", "b");

}

@Override

public void debug(String format, Object arg1, Object arg2) {

logger.logIfEnabled(FQCN, Level.DEBUG, null, format,
arg1, arg2);

}
void logIfEnabled(String fqcn, Level level,
Marker marker, String message, Object... params);
String::contains Quiz
String::contains Quiz
String containsTest = "contains or not?";

StringBuilder builder = new StringBuilder("Test string that
is long");



while (true) {

if (containsTest.contains(builder)) {

System.out.println("Contains! (??)");

}

}
String::contains Quiz
public boolean contains(CharSequence s) {

return indexOf(s.toString()) > -1;

}
Sins of the young… GC
Stop the world
Sins of the young… GC
Stop the world
Time proportional to number of surviving objects
Sins of the young… GC
Stop the world
Time proportional to number of surviving objects
and old gen size (card scanning!)
Card table
Old gen: X MB
Card table (X*2000 entries)
Sins of the young… GC
Stop the world
Time proportional to number of surviving objects
and old gen size (card scanning!)
Trashing processor caches, TLB, page table, NUMA
Intel cache hierarchies
L1 & L2 caches are core local
L3 is shared among all cores
in a socket
contains all data in L1 & L2
Putting data into local
cache of one core may
evict data from local
caches of another core
Sins of the young… GC
No algorithm is lock free (let alone wait free) if it
allocates objects on its critical path
Amdahl’s Law
…the effort expended on achieving high parallel
processing rates is wasted unless it is accompanied by
achievements in sequential processing rates of very
nearly the same magnitude.
1%
1024
Serial part is time spent in GC
2%
3%
Escape analysis
After escape analysis, the server compiler eliminates
scalar replaceable object allocations and associated
locks from generated code. The server compiler also
eliminates locks for all non-globally escaping objects. It
does not replace a heap allocation with a stack
allocation for non-globally escaping objects.
https://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance-
enhancements-7.html#escapeAnalysis
Profiling
YourKit et al.
Java Mission Control
Beware of false positives
http://psy-lob-saw.blogspot.de/2014/12/the-
escape-of-arraylistiterator.html
Basic techniques
Use ThreadLocal objects
Created on first use
Confined to single thread
Less effective if threads are short lived or there are
thousands of them
JDK already uses this pattern
JDK Use of Thread Locals
• StringCoding:



private final static
ThreadLocal<SoftReference<StringDecoder>> decoder =

new ThreadLocal<>();


private final static
ThreadLocal<SoftReference<StringEncoder>> encoder =

new ThreadLocal<>();

•ThreadLocalCoders.encoderFor(“UTF-8”)
•ThreadLocalRandom
Strings
In Java 8
No easy way to getBytes of a string without allocating new
array
No easy way to encode/decode strings without allocation
I Java 9 (thanks to Richard Warburton)
Creating new Strings from ByteBuffer and Charset
getBytes with externally provided byte array or ByteBuffer and
Charset
ConcurrentHashMap::size
Java 6 Java 8
int[] mc = new int[segments.length];
// Try a few times to get accurate count.
// On failure due to
// continuous async changes in table,
// resort to locking.
for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
for (int i = 0; i < segments.length; ++i) {
sum += segments[i].count;
mcsum += mc[i] = segments[i].modCount;
}
...
CounterCell[] as = counterCells; CounterCell a;

long sum = baseCount;

if (as != null) {
for (int i = 0; i < as.length; ++i) {

if ((a = as[i]) != null)

sum += a.value;

}

}


return sum;
•Allocate array
•Put segment sizes in it
•Lock everything if modCount
changes
•Sum per segment size counters
updated by other operations
Splitter (Guava)
Alternative to
public String[] split(String regex)
Splitter (Guava)
public Iterable<String> split(final CharSequence sequence)
Splitter (Guava)
public Iterable<String> split(final CharSequence sequence)
Dose not force caller to use immutable String
Splitter (Guava)
public Iterable<String> split(final CharSequence sequence)
Dose not force caller to use immutable String
Returns minimal interface that does the job
Does not commit to creating new collection object
(List<String> etc.) Will return next token when asked for
The bad: will return new String for each token
Compare to String[] String.split(String)
API is the key
String[] String.split(String)
vs
Iterable<String> Splitter.split(final CharSequence sequence)
byte[] String.getBytes()
vs.
String.getBytes(byte[] copyTo, int offset);
Conclusion
If not for GC pauses we would not care at all about allocation.
We would look at it ONLY when there are performance
hotspots in code related to object construction and
initialisation.
API is the key, well designed gives freedom:
for users to choose version that allocates or reuses user
supplied objects
for implementers to optimise in time without changing API
Bonus: collections options
https://github.com/OpenHFT/Koloboke
Fast, space efficient
Uses one array to lay out keys and values
Provides hash sets, hash maps
With primitive specialisation
“Project was started as a Trove fork, but has nothing in common with Trove for already very
long time”
Cliff Clicks’ High Scale Lib
http://sourceforge.net/projects/high-scale-lib/
Old stuff but might still scale better

More Related Content

What's hot

Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSOswald Campesato
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerIslam Sharabash
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016Frank Lyaruu
 
CLS & asyncListener: asynchronous observability for Node.js
CLS & asyncListener: asynchronous observability for Node.jsCLS & asyncListener: asynchronous observability for Node.js
CLS & asyncListener: asynchronous observability for Node.jsForrest Norvell
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Tutorial - 16 : How to pass parameters from one script to another by CallScri...
Tutorial - 16 : How to pass parameters from one script to another by CallScri...Tutorial - 16 : How to pass parameters from one script to another by CallScri...
Tutorial - 16 : How to pass parameters from one script to another by CallScri...Yogindernath Gupta
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guideAdy Liu
 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac pluginOleksandr Radchykov
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroidSavvycom Savvycom
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidEgor Andreevich
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015Constantine Mars
 
Jafka guide
Jafka guideJafka guide
Jafka guideAdy Liu
 

What's hot (20)

Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListenerNode.js: Continuation-Local-Storage and the Magic of AsyncListener
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
 
RxJava Applied
RxJava AppliedRxJava Applied
RxJava Applied
 
CLS & asyncListener: asynchronous observability for Node.js
CLS & asyncListener: asynchronous observability for Node.jsCLS & asyncListener: asynchronous observability for Node.js
CLS & asyncListener: asynchronous observability for Node.js
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
Tutorial - 16 : How to pass parameters from one script to another by CallScri...
Tutorial - 16 : How to pass parameters from one script to another by CallScri...Tutorial - 16 : How to pass parameters from one script to another by CallScri...
Tutorial - 16 : How to pass parameters from one script to another by CallScri...
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guide
 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac plugin
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Reactive programming with RxAndroid
Reactive programming with RxAndroidReactive programming with RxAndroid
Reactive programming with RxAndroid
 
Intro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich AndroidIntro to RxJava/RxAndroid - GDG Munich Android
Intro to RxJava/RxAndroid - GDG Munich Android
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015
 
Jafka guide
Jafka guideJafka guide
Jafka guide
 

Viewers also liked

Succession process among africa owned business in uk
Succession process among africa owned business in ukSuccession process among africa owned business in uk
Succession process among africa owned business in ukJohn Johari
 
Лояльность в МСБ (ФГ Лайф, Захаров)
Лояльность в МСБ (ФГ Лайф, Захаров)Лояльность в МСБ (ФГ Лайф, Захаров)
Лояльность в МСБ (ФГ Лайф, Захаров)Alexey Zakharov
 
Orthoapnea - Dental Practice (australasian)
Orthoapnea - Dental Practice (australasian)Orthoapnea - Dental Practice (australasian)
Orthoapnea - Dental Practice (australasian)OrthoApnea
 
Software Mühəndisliyinin Hüquqi, Sosial və Etik Tərəfləri
Software Mühəndisliyinin  Hüquqi, Sosial və Etik TərəfləriSoftware Mühəndisliyinin  Hüquqi, Sosial və Etik Tərəfləri
Software Mühəndisliyinin Hüquqi, Sosial və Etik TərəfləriRufatet Babakishiyev
 
Marketing Slides
Marketing SlidesMarketing Slides
Marketing SlidesUmazar
 
The great American civilizations: The mayas
The great American civilizations: The mayasThe great American civilizations: The mayas
The great American civilizations: The mayasGladimar Marín
 
Content Marketing to Drive High Quality Links - SMX West 2015 - SEO Track
Content Marketing to Drive High Quality Links - SMX West 2015 - SEO TrackContent Marketing to Drive High Quality Links - SMX West 2015 - SEO Track
Content Marketing to Drive High Quality Links - SMX West 2015 - SEO TrackPurna Virji
 
SLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 Gigawatts
SLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 GigawattsSLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 Gigawatts
SLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 GigawattsClix Marketing
 
Domotica E Risparmio Energetico
Domotica E Risparmio EnergeticoDomotica E Risparmio Energetico
Domotica E Risparmio Energeticovhdelcastano68
 

Viewers also liked (12)

Proyecto de ley n
Proyecto de ley nProyecto de ley n
Proyecto de ley n
 
Webcasting
WebcastingWebcasting
Webcasting
 
Succession process among africa owned business in uk
Succession process among africa owned business in ukSuccession process among africa owned business in uk
Succession process among africa owned business in uk
 
Лояльность в МСБ (ФГ Лайф, Захаров)
Лояльность в МСБ (ФГ Лайф, Захаров)Лояльность в МСБ (ФГ Лайф, Захаров)
Лояльность в МСБ (ФГ Лайф, Захаров)
 
Orthoapnea - Dental Practice (australasian)
Orthoapnea - Dental Practice (australasian)Orthoapnea - Dental Practice (australasian)
Orthoapnea - Dental Practice (australasian)
 
Software Mühəndisliyinin Hüquqi, Sosial və Etik Tərəfləri
Software Mühəndisliyinin  Hüquqi, Sosial və Etik TərəfləriSoftware Mühəndisliyinin  Hüquqi, Sosial və Etik Tərəfləri
Software Mühəndisliyinin Hüquqi, Sosial və Etik Tərəfləri
 
Marketing Slides
Marketing SlidesMarketing Slides
Marketing Slides
 
The great American civilizations: The mayas
The great American civilizations: The mayasThe great American civilizations: The mayas
The great American civilizations: The mayas
 
Content Marketing to Drive High Quality Links - SMX West 2015 - SEO Track
Content Marketing to Drive High Quality Links - SMX West 2015 - SEO TrackContent Marketing to Drive High Quality Links - SMX West 2015 - SEO Track
Content Marketing to Drive High Quality Links - SMX West 2015 - SEO Track
 
KCB101 - Assessment 2
KCB101 - Assessment 2KCB101 - Assessment 2
KCB101 - Assessment 2
 
SLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 Gigawatts
SLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 GigawattsSLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 Gigawatts
SLCSEM - Remarketing: Using Past Data to Take Your Marketing to 1.21 Gigawatts
 
Domotica E Risparmio Energetico
Domotica E Risparmio EnergeticoDomotica E Risparmio Energetico
Domotica E Risparmio Energetico
 

Similar to Forgive me for i have allocated

.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance TuningMinh Hoang
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lispelliando dias
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinaloscon2007
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinaloscon2007
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 

Similar to Forgive me for i have allocated (20)

Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Collections forceawakens
Collections forceawakensCollections forceawakens
Collections forceawakens
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
G pars
G parsG pars
G pars
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 

More from Tomasz Kowalczewski

How I learned to stop worrying and love the dark silicon apocalypse.pdf
How I learned to stop worrying and love the dark silicon apocalypse.pdfHow I learned to stop worrying and love the dark silicon apocalypse.pdf
How I learned to stop worrying and love the dark silicon apocalypse.pdfTomasz Kowalczewski
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive? Tomasz Kowalczewski
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive? Tomasz Kowalczewski
 
Is writing performant code too expensive?
Is writing performant code too expensive?Is writing performant code too expensive?
Is writing performant code too expensive?Tomasz Kowalczewski
 
Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)Tomasz Kowalczewski
 

More from Tomasz Kowalczewski (12)

How I learned to stop worrying and love the dark silicon apocalypse.pdf
How I learned to stop worrying and love the dark silicon apocalypse.pdfHow I learned to stop worrying and love the dark silicon apocalypse.pdf
How I learned to stop worrying and love the dark silicon apocalypse.pdf
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Is writing performant code too expensive?
Is writing performant code too expensive?Is writing performant code too expensive?
Is writing performant code too expensive?
 
Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)Deep dive reactive java (DevoxxPl)
Deep dive reactive java (DevoxxPl)
 
Everybody Lies
Everybody LiesEverybody Lies
Everybody Lies
 
Measure to fail
Measure to failMeasure to fail
Measure to fail
 
Reactive Java at JDD 2014
Reactive Java at JDD 2014Reactive Java at JDD 2014
Reactive Java at JDD 2014
 
Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)Reactive Java (GeeCON 2014)
Reactive Java (GeeCON 2014)
 
Introduction to Reactive Java
Introduction to Reactive JavaIntroduction to Reactive Java
Introduction to Reactive Java
 
Java 8 jest tuż za rogiem
Java 8 jest tuż za rogiemJava 8 jest tuż za rogiem
Java 8 jest tuż za rogiem
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 

Recently uploaded

UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 

Forgive me for i have allocated

  • 1. Forgive me for I have allocated Tomasz Kowalczewski
  • 3. Log4j2 Logger Quiz How many objects does this loop create when debug logging is disabled? while (true) {
 LOGGER.debug("{} {}", "a", "b");
 }

  • 4. Log4j2 Logger while (true) {
 LOGGER.debug("{} {}", "a", "b");
 }
 @Override
 public void debug(String format, Object arg1, Object arg2) {
 logger.logIfEnabled(FQCN, Level.DEBUG, null, format, arg1, arg2);
 } void logIfEnabled(String fqcn, Level level, Marker marker, String message, Object... params);
  • 6. String::contains Quiz String containsTest = "contains or not?";
 StringBuilder builder = new StringBuilder("Test string that is long");
 
 while (true) {
 if (containsTest.contains(builder)) {
 System.out.println("Contains! (??)");
 }
 }
  • 7. String::contains Quiz public boolean contains(CharSequence s) {
 return indexOf(s.toString()) > -1;
 }
  • 8. Sins of the young… GC Stop the world
  • 9. Sins of the young… GC Stop the world Time proportional to number of surviving objects
  • 10. Sins of the young… GC Stop the world Time proportional to number of surviving objects and old gen size (card scanning!)
  • 11. Card table Old gen: X MB Card table (X*2000 entries)
  • 12. Sins of the young… GC Stop the world Time proportional to number of surviving objects and old gen size (card scanning!) Trashing processor caches, TLB, page table, NUMA
  • 13. Intel cache hierarchies L1 & L2 caches are core local L3 is shared among all cores in a socket contains all data in L1 & L2 Putting data into local cache of one core may evict data from local caches of another core
  • 14. Sins of the young… GC No algorithm is lock free (let alone wait free) if it allocates objects on its critical path
  • 15. Amdahl’s Law …the effort expended on achieving high parallel processing rates is wasted unless it is accompanied by achievements in sequential processing rates of very nearly the same magnitude.
  • 16. 1% 1024 Serial part is time spent in GC 2% 3%
  • 17. Escape analysis After escape analysis, the server compiler eliminates scalar replaceable object allocations and associated locks from generated code. The server compiler also eliminates locks for all non-globally escaping objects. It does not replace a heap allocation with a stack allocation for non-globally escaping objects. https://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance- enhancements-7.html#escapeAnalysis
  • 18. Profiling YourKit et al. Java Mission Control Beware of false positives http://psy-lob-saw.blogspot.de/2014/12/the- escape-of-arraylistiterator.html
  • 19. Basic techniques Use ThreadLocal objects Created on first use Confined to single thread Less effective if threads are short lived or there are thousands of them JDK already uses this pattern
  • 20. JDK Use of Thread Locals • StringCoding:
 
 private final static ThreadLocal<SoftReference<StringDecoder>> decoder =
 new ThreadLocal<>(); 
 private final static ThreadLocal<SoftReference<StringEncoder>> encoder =
 new ThreadLocal<>();
 •ThreadLocalCoders.encoderFor(“UTF-8”) •ThreadLocalRandom
  • 21. Strings In Java 8 No easy way to getBytes of a string without allocating new array No easy way to encode/decode strings without allocation I Java 9 (thanks to Richard Warburton) Creating new Strings from ByteBuffer and Charset getBytes with externally provided byte array or ByteBuffer and Charset
  • 22. ConcurrentHashMap::size Java 6 Java 8 int[] mc = new int[segments.length]; // Try a few times to get accurate count. // On failure due to // continuous async changes in table, // resort to locking. for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) { for (int i = 0; i < segments.length; ++i) { sum += segments[i].count; mcsum += mc[i] = segments[i].modCount; } ... CounterCell[] as = counterCells; CounterCell a;
 long sum = baseCount;
 if (as != null) { for (int i = 0; i < as.length; ++i) {
 if ((a = as[i]) != null)
 sum += a.value;
 }
 } 
 return sum; •Allocate array •Put segment sizes in it •Lock everything if modCount changes •Sum per segment size counters updated by other operations
  • 23. Splitter (Guava) Alternative to public String[] split(String regex)
  • 24. Splitter (Guava) public Iterable<String> split(final CharSequence sequence)
  • 25. Splitter (Guava) public Iterable<String> split(final CharSequence sequence) Dose not force caller to use immutable String
  • 26. Splitter (Guava) public Iterable<String> split(final CharSequence sequence) Dose not force caller to use immutable String Returns minimal interface that does the job Does not commit to creating new collection object (List<String> etc.) Will return next token when asked for The bad: will return new String for each token Compare to String[] String.split(String)
  • 27. API is the key String[] String.split(String) vs Iterable<String> Splitter.split(final CharSequence sequence) byte[] String.getBytes() vs. String.getBytes(byte[] copyTo, int offset);
  • 28. Conclusion If not for GC pauses we would not care at all about allocation. We would look at it ONLY when there are performance hotspots in code related to object construction and initialisation. API is the key, well designed gives freedom: for users to choose version that allocates or reuses user supplied objects for implementers to optimise in time without changing API
  • 29. Bonus: collections options https://github.com/OpenHFT/Koloboke Fast, space efficient Uses one array to lay out keys and values Provides hash sets, hash maps With primitive specialisation “Project was started as a Trove fork, but has nothing in common with Trove for already very long time” Cliff Clicks’ High Scale Lib http://sourceforge.net/projects/high-scale-lib/ Old stuff but might still scale better