SlideShare a Scribd company logo
Java Performance Tuning Minh Hoang TO Portal Team
Agenda Performance Measure   JRE Customization  Programming Tips Reading Suggestions
Performance Measure
Performance Measure Performance Analytical Tools Determine problem Attack performance problem
Performance Analytical Tools JDK tools: JVisualVM (since Java 6), JConsole Commercial tools: JProfiler
Determine problem Factor to improve? Time or Memory Quantitative analysis to encircle the root causes Use tools to localize memory leak, method call overhead Theoretical argument servers for first-step analysis, but tools provide most convincing information
Attack performance problem Improve execution environment Examine programming aspect
JRE Customization
JRE Customization JVM Options Customize Garbage Collection Frequently used JVM options
JVM Options JAVA_HOME/java JAVA_HOME/java -X
Customize Garbage Collection JAVA_HOME/java -X   -Xnoclassgc -Xincgc
Frequently used JVM options Heap size options -Xms -Xmx Permanent Generation options -XX:MaxPermSize Class sharing -Xshare
Programming Tips
Programming Tips Object Creation String Collection Framework Java IO and NIO (for next time) Concurrency
Object Creation Object scope final   modifier Interaction with Garbage Collector
Object Scope String wideScope;  for(int  i =0; i <10000000; i++) {   wideScope = “” + i; } vs for(int i = 0; i < 10000000; i++) { String narrowScope = “” + i; }
Heap space is divided into  Young Generation  and  Old Generation  spaces JAVA_HOME/jconsole Garbage Collector has best performance on  Young Generation Object with narrow scope has more chance to stay in  Young Generation
Final modifier Protect variable against reference reassignment (non-reflect code) final SafeObject safeObject = new SafeObject(); safeObject = null; // compilation error Modularize code with anonymous class final String displayString = “Hello”; Runnable runnable = new Runnable(){ public void run() { System.out.println(displayString); } };
Final modifier Affect of  final  at execution Look at my  IntelliJ IDEA 10
Interaction with Garbage Collector GC   (Garbage Collector) reclaims memory occupied by unreferenced object TestObject strongReference = new TestObject();  //variable strongReference //points to memory cells at 0xXXXX  strongReference = null; //no reference to cells 0xXXXX System.gc();  //Run the GC GC  handles  SoftReference ,  WeakReference  and  PhantomReference  exceptionally JavaDoc from package  java.lang.ref
//Object is allocated at 0xXXXX TestObject  strongReference = new TestObject();  SoftReference<TestObject> softReference = new SoftReference<TestObject>(strongReference);  //Object stored at 0xXXX is reachable from softReference strongReference = null;  //No more strong reference to object  Object stored at 0xXXXX is softly reachable from softReference, but  automatically cleaned  by  GC  when  there is lack of memory
Code from LazyList class of GateIn private static class Batch { private final Reference<Object[]> elements; private Batch(Object[] elements) { this.elements = new SoftReference<Object[]>(elements); } }
String String Thread-safe, expensive handling methods StringBuffer Thread-safe, much faster than  String StringBuilder Not thread-safe, slightly faster than  StringBuffer
String s = new String(); for(int i = 0; i < 10000; i++){ s += “a”; } VS StringBuffer buffer = new StringBuffer(); for(int i = 0; i < 10000; i++){ buffer.append(“a”); } VS StringBuilder builder = new StringBuilder(); for(int i = 0; i < 10000; i++){ builder.append(“a”); }
Collection Framework Random Access vs Sequential Initial allocation HashMap vs TreeMap WeakHashMap
Random Access vs Sequential ArrayList<E> access element: O(1) add element at the end: O(1) or O(n)   sort element: O(n.logn)  (sort with Collections.sort()) LinkedList<E> access element: O(n) add element at both ends: O(1) sort element: O(n.logn) + O(n)  (sort with Collections.sort())
Initial Allocation Code snippet recurring in eXo products List<String> list = new ArrayList<String>(3); Why hard-coded size? Is it better than List<String> list = new LinkedList<String>();
HashMap vs TreeMap HashMap<K,V> fetch <K,V> entry: O(1) put <K,V> entry: O(n) in worst case sort <K,V> entries based on key: Not supported TreeMap<K,V> fetch <K,V> entry: O(1) Put <K,V> entry: O(n) in worst case support sorting entries based on key
WeakHashMap private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> { private V value; private final int hash; private Entry<K,V> next; … . }
Java IO and NIO In many cases: gainOf(  improve_on_programming_logic  )  <<<< gainOf(  improve_on_input_output ) Java coder should have knowledge on Java NIO
Concurrency Concurrency concepts Intrinsic lock volatile  keyword Lock & Lock-free
Concurrency concepts Atomicity Code executing on a thread is not inteferenced with other threads Ex:  Code incrementing a counter Visibility Change  on shared object is visible to multiple threads Ex:  Flag variable
Atomicity  yields  Visibility Atomicity  problems are more complex than  Visibility  ones Figure out your concurrency problem ( Atomicity  or  Visibility ) before typing  synchronized
Intrinsic lock -  synchronized Ensure   Atomicity Overhead of synchronized   Double-checked pattern 'intrinsic lock extension' in  java.util.concurrent.locks
private int counter; private void increaseCounter(){ counter++;} private synchronized void increaseCounterUsingIntrinsicLock(){ counter++;} public static void main(String[] args) {   int n = 100000;   //Print time to call increaseCounter  n times  //Print time to call  increaseCounterUsingIntrinsicLock n times }
Double-checked pattern synchronized( locked_object ) {   if( flag_variable ){ //do something } } VS if( flag_variable ){   synchronized( locked_object ) {   if( flag_variable ){ //do something }   } }
Double-checked reduces the scope of  synchronized  block Useful in concurrent initialization problem Requires  Visibility  on  flag_variable
Code from RootContainer class in eXo Kernel public static RootContainer getInstance() { RootContainer result = singleton_; if (result == null) { synchronized (RootContainer.class)   {….}   }  }
Code from Component class in WebUI Framework public Event getUIComponentEventConfig(String eventName) throws Exception { if(eventMap == null) { synchronized(this) { if(eventMap == null) {…}   } } }
Volatile keyword Ensure  Visibility Work only with atomic operations Usage in double-checked pattern 'volatile extension' in  java.util.concurrent.atomic
private volatile long counter; private void nonAtomicOperation(){ counter++;} private void atomicOperation(){ counter = 281283;}
Usage in double-checked pattern Java Memory Model permutes execution order in multi-thread world (JVM Specification) Visibility  on flag_variable is mandatory to double-checked pattern volatile boolean flag_variable;  //Assumed the type is boolean //Double-checked block
Lock & Lock-free Lock Package  java.util.concurrent.locks Lock-free Package  java.util.concurrent.atomic
Reading Suggestions
Java Concurrency in Practice – Brian Goetz Java IO  Java NIO
Thank you!

More Related Content

What's hot (20)

PPTX
The Java Memory Model
CA Technologies
 
PDF
JVM JIT-compiler overview @ JavaOne Moscow 2013
Vladimir Ivanov
 
PDF
Why GC is eating all my CPU?
Roman Elizarov
 
PDF
Intrinsic Methods in HotSpot VM
Kris Mok
 
PDF
Using Flame Graphs
Isuru Perera
 
ODP
Java Garbage Collection, Monitoring, and Tuning
Carol McDonald
 
PPTX
HotSpot JVM Tuning
Gilad Garon
 
PPT
An Introduction to JVM Internals and Garbage Collection in Java
Abhishek Asthana
 
PPTX
Java Serialization Facts and Fallacies
Roman Elizarov
 
PPTX
DIY Java Profiling
Roman Elizarov
 
PDF
Wait for your fortune without Blocking!
Roman Elizarov
 
KEY
JavaOne 2011 - JVM Bytecode for Dummies
Charles Nutter
 
PPT
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
Kwangshin Oh
 
KEY
Know yourengines velocity2011
Demis Bellot
 
PPTX
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
PDF
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
Vladimir Ivanov
 
PPT
iOS Multithreading
Richa Jain
 
PDF
Software Profiling: Understanding Java Performance and how to profile in Java
Isuru Perera
 
PDF
Loom and concurrency latest
Srinivasan Raghavan
 
The Java Memory Model
CA Technologies
 
JVM JIT-compiler overview @ JavaOne Moscow 2013
Vladimir Ivanov
 
Why GC is eating all my CPU?
Roman Elizarov
 
Intrinsic Methods in HotSpot VM
Kris Mok
 
Using Flame Graphs
Isuru Perera
 
Java Garbage Collection, Monitoring, and Tuning
Carol McDonald
 
HotSpot JVM Tuning
Gilad Garon
 
An Introduction to JVM Internals and Garbage Collection in Java
Abhishek Asthana
 
Java Serialization Facts and Fallacies
Roman Elizarov
 
DIY Java Profiling
Roman Elizarov
 
Wait for your fortune without Blocking!
Roman Elizarov
 
JavaOne 2011 - JVM Bytecode for Dummies
Charles Nutter
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
Kwangshin Oh
 
Know yourengines velocity2011
Demis Bellot
 
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
"JIT compiler overview" @ JEEConf 2013, Kiev, Ukraine
Vladimir Ivanov
 
iOS Multithreading
Richa Jain
 
Software Profiling: Understanding Java Performance and how to profile in Java
Isuru Perera
 
Loom and concurrency latest
Srinivasan Raghavan
 

Viewers also liked (20)

PPT
Jvm Performance Tunning
Terry Cho
 
PPTX
Java性能调优浅谈
jxqlovejava
 
PDF
Hotspot Garbage Collection - The Useful Parts
jClarity
 
PPTX
Java performance tuning
Jerry Kurian
 
PPTX
Sun jdk 1.6内存管理 -使用篇
bluedavy lin
 
PPTX
Hands-on Performance Tuning Lab - Devoxx Poland
C2B2 Consulting
 
PPTX
Java profiling Do It Yourself
aragozin
 
PDF
Diagnosing Your Application on the JVM
Staffan Larsen
 
PDF
JavaOne 2014: Java Debugging
Chris Bailey
 
PDF
Profiler Guided Java Performance Tuning
osa_ora
 
PDF
Debugging Your Production JVM
kensipe
 
PDF
Performance optimization techniques for Java code
Attila Balazs
 
PPTX
Memory leak
Anandraj Kulkarni
 
PPT
Efficient Memory and Thread Management in Highly Parallel Java Applications
pkoza
 
PDF
Memory Leak In java
Mindfire Solutions
 
PPT
Real Life Java EE Performance Tuning
C2B2 Consulting
 
ODP
An Introduction To Java Profiling
schlebu
 
PPTX
Benchmarking Solr Performance
Lucidworks
 
PDF
Introduction of Java GC Tuning and Java Java Mission Control
Leon Chen
 
PDF
High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...
Lucidworks
 
Jvm Performance Tunning
Terry Cho
 
Java性能调优浅谈
jxqlovejava
 
Hotspot Garbage Collection - The Useful Parts
jClarity
 
Java performance tuning
Jerry Kurian
 
Sun jdk 1.6内存管理 -使用篇
bluedavy lin
 
Hands-on Performance Tuning Lab - Devoxx Poland
C2B2 Consulting
 
Java profiling Do It Yourself
aragozin
 
Diagnosing Your Application on the JVM
Staffan Larsen
 
JavaOne 2014: Java Debugging
Chris Bailey
 
Profiler Guided Java Performance Tuning
osa_ora
 
Debugging Your Production JVM
kensipe
 
Performance optimization techniques for Java code
Attila Balazs
 
Memory leak
Anandraj Kulkarni
 
Efficient Memory and Thread Management in Highly Parallel Java Applications
pkoza
 
Memory Leak In java
Mindfire Solutions
 
Real Life Java EE Performance Tuning
C2B2 Consulting
 
An Introduction To Java Profiling
schlebu
 
Benchmarking Solr Performance
Lucidworks
 
Introduction of Java GC Tuning and Java Java Mission Control
Leon Chen
 
High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...
Lucidworks
 
Ad

Similar to Java Performance Tuning (20)

PPT
Java programing considering performance
Roger Xia
 
ODP
Best practices in Java
Mudit Gupta
 
KEY
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
PPT
Hs java open_party
Open Party
 
PPTX
Java concurrency
Hithem Ahmed
 
PDF
Java Concurrency Gotchas
Alex Miller
 
KEY
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Charles Nutter
 
PDF
Designing and coding Series 40 Java apps for high performance
Microsoft Mobile Developer
 
PPT
Concurrency Antipatterns In IDEA
cdracm
 
PPTX
Jvm memory model
Yoav Avrahami
 
PPT
Optimizing your java applications for multi core hardware
IndicThreads
 
PDF
Java Concurrency Gotchas
Alex Miller
 
PPT
Garbage collection in JVM
aragozin
 
PDF
Concurrency Concepts in Java
Doug Hawkins
 
PDF
Concurrency gotchas
Jitender Jain
 
PDF
JAVA Interview Questions (1)............pdf
prasadkhotkar916
 
PDF
JAVA Interview Questions (1)..........pdf
prasadkhotkar916
 
PPT
Performance tuning jvm
Prem Kuppumani
 
PDF
Javaoneconcurrencygotchas 090610192215 Phpapp02
Tarun Kumar
 
PPTX
Concurrency Grabbag
Debashis Saha
 
Java programing considering performance
Roger Xia
 
Best practices in Java
Mudit Gupta
 
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
Hs java open_party
Open Party
 
Java concurrency
Hithem Ahmed
 
Java Concurrency Gotchas
Alex Miller
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Charles Nutter
 
Designing and coding Series 40 Java apps for high performance
Microsoft Mobile Developer
 
Concurrency Antipatterns In IDEA
cdracm
 
Jvm memory model
Yoav Avrahami
 
Optimizing your java applications for multi core hardware
IndicThreads
 
Java Concurrency Gotchas
Alex Miller
 
Garbage collection in JVM
aragozin
 
Concurrency Concepts in Java
Doug Hawkins
 
Concurrency gotchas
Jitender Jain
 
JAVA Interview Questions (1)............pdf
prasadkhotkar916
 
JAVA Interview Questions (1)..........pdf
prasadkhotkar916
 
Performance tuning jvm
Prem Kuppumani
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Tarun Kumar
 
Concurrency Grabbag
Debashis Saha
 
Ad

More from Minh Hoang (7)

PDF
Yolo Family TechTalk
Minh Hoang
 
PDF
ElasticSearch Introduction
Minh Hoang
 
PDF
Modularize JavaScript with RequireJS
Minh Hoang
 
PPT
Zero redeployment with JRebel
Minh Hoang
 
PPT
Servlet 3.0
Minh Hoang
 
PPT
Regular Expression
Minh Hoang
 
PDF
Gatein Presentation
Minh Hoang
 
Yolo Family TechTalk
Minh Hoang
 
ElasticSearch Introduction
Minh Hoang
 
Modularize JavaScript with RequireJS
Minh Hoang
 
Zero redeployment with JRebel
Minh Hoang
 
Servlet 3.0
Minh Hoang
 
Regular Expression
Minh Hoang
 
Gatein Presentation
Minh Hoang
 

Recently uploaded (20)

PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
July Patch Tuesday
Ivanti
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Biography of Daniel Podor.pdf
Daniel Podor
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 

Java Performance Tuning

  • 1. Java Performance Tuning Minh Hoang TO Portal Team
  • 2. Agenda Performance Measure JRE Customization Programming Tips Reading Suggestions
  • 4. Performance Measure Performance Analytical Tools Determine problem Attack performance problem
  • 5. Performance Analytical Tools JDK tools: JVisualVM (since Java 6), JConsole Commercial tools: JProfiler
  • 6. Determine problem Factor to improve? Time or Memory Quantitative analysis to encircle the root causes Use tools to localize memory leak, method call overhead Theoretical argument servers for first-step analysis, but tools provide most convincing information
  • 7. Attack performance problem Improve execution environment Examine programming aspect
  • 9. JRE Customization JVM Options Customize Garbage Collection Frequently used JVM options
  • 10. JVM Options JAVA_HOME/java JAVA_HOME/java -X
  • 11. Customize Garbage Collection JAVA_HOME/java -X -Xnoclassgc -Xincgc
  • 12. Frequently used JVM options Heap size options -Xms -Xmx Permanent Generation options -XX:MaxPermSize Class sharing -Xshare
  • 14. Programming Tips Object Creation String Collection Framework Java IO and NIO (for next time) Concurrency
  • 15. Object Creation Object scope final modifier Interaction with Garbage Collector
  • 16. Object Scope String wideScope; for(int i =0; i <10000000; i++) { wideScope = “” + i; } vs for(int i = 0; i < 10000000; i++) { String narrowScope = “” + i; }
  • 17. Heap space is divided into Young Generation and Old Generation spaces JAVA_HOME/jconsole Garbage Collector has best performance on Young Generation Object with narrow scope has more chance to stay in Young Generation
  • 18. Final modifier Protect variable against reference reassignment (non-reflect code) final SafeObject safeObject = new SafeObject(); safeObject = null; // compilation error Modularize code with anonymous class final String displayString = “Hello”; Runnable runnable = new Runnable(){ public void run() { System.out.println(displayString); } };
  • 19. Final modifier Affect of final at execution Look at my IntelliJ IDEA 10
  • 20. Interaction with Garbage Collector GC (Garbage Collector) reclaims memory occupied by unreferenced object TestObject strongReference = new TestObject(); //variable strongReference //points to memory cells at 0xXXXX strongReference = null; //no reference to cells 0xXXXX System.gc(); //Run the GC GC handles SoftReference , WeakReference and PhantomReference exceptionally JavaDoc from package java.lang.ref
  • 21. //Object is allocated at 0xXXXX TestObject strongReference = new TestObject(); SoftReference<TestObject> softReference = new SoftReference<TestObject>(strongReference); //Object stored at 0xXXX is reachable from softReference strongReference = null; //No more strong reference to object Object stored at 0xXXXX is softly reachable from softReference, but automatically cleaned by GC when there is lack of memory
  • 22. Code from LazyList class of GateIn private static class Batch { private final Reference<Object[]> elements; private Batch(Object[] elements) { this.elements = new SoftReference<Object[]>(elements); } }
  • 23. String String Thread-safe, expensive handling methods StringBuffer Thread-safe, much faster than String StringBuilder Not thread-safe, slightly faster than StringBuffer
  • 24. String s = new String(); for(int i = 0; i < 10000; i++){ s += “a”; } VS StringBuffer buffer = new StringBuffer(); for(int i = 0; i < 10000; i++){ buffer.append(“a”); } VS StringBuilder builder = new StringBuilder(); for(int i = 0; i < 10000; i++){ builder.append(“a”); }
  • 25. Collection Framework Random Access vs Sequential Initial allocation HashMap vs TreeMap WeakHashMap
  • 26. Random Access vs Sequential ArrayList<E> access element: O(1) add element at the end: O(1) or O(n) sort element: O(n.logn) (sort with Collections.sort()) LinkedList<E> access element: O(n) add element at both ends: O(1) sort element: O(n.logn) + O(n) (sort with Collections.sort())
  • 27. Initial Allocation Code snippet recurring in eXo products List<String> list = new ArrayList<String>(3); Why hard-coded size? Is it better than List<String> list = new LinkedList<String>();
  • 28. HashMap vs TreeMap HashMap<K,V> fetch <K,V> entry: O(1) put <K,V> entry: O(n) in worst case sort <K,V> entries based on key: Not supported TreeMap<K,V> fetch <K,V> entry: O(1) Put <K,V> entry: O(n) in worst case support sorting entries based on key
  • 29. WeakHashMap private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> { private V value; private final int hash; private Entry<K,V> next; … . }
  • 30. Java IO and NIO In many cases: gainOf( improve_on_programming_logic ) <<<< gainOf( improve_on_input_output ) Java coder should have knowledge on Java NIO
  • 31. Concurrency Concurrency concepts Intrinsic lock volatile keyword Lock & Lock-free
  • 32. Concurrency concepts Atomicity Code executing on a thread is not inteferenced with other threads Ex: Code incrementing a counter Visibility Change on shared object is visible to multiple threads Ex: Flag variable
  • 33. Atomicity yields Visibility Atomicity problems are more complex than Visibility ones Figure out your concurrency problem ( Atomicity or Visibility ) before typing synchronized
  • 34. Intrinsic lock - synchronized Ensure Atomicity Overhead of synchronized Double-checked pattern 'intrinsic lock extension' in java.util.concurrent.locks
  • 35. private int counter; private void increaseCounter(){ counter++;} private synchronized void increaseCounterUsingIntrinsicLock(){ counter++;} public static void main(String[] args) { int n = 100000; //Print time to call increaseCounter n times //Print time to call increaseCounterUsingIntrinsicLock n times }
  • 36. Double-checked pattern synchronized( locked_object ) { if( flag_variable ){ //do something } } VS if( flag_variable ){ synchronized( locked_object ) { if( flag_variable ){ //do something } } }
  • 37. Double-checked reduces the scope of synchronized block Useful in concurrent initialization problem Requires Visibility on flag_variable
  • 38. Code from RootContainer class in eXo Kernel public static RootContainer getInstance() { RootContainer result = singleton_; if (result == null) { synchronized (RootContainer.class) {….} } }
  • 39. Code from Component class in WebUI Framework public Event getUIComponentEventConfig(String eventName) throws Exception { if(eventMap == null) { synchronized(this) { if(eventMap == null) {…} } } }
  • 40. Volatile keyword Ensure Visibility Work only with atomic operations Usage in double-checked pattern 'volatile extension' in java.util.concurrent.atomic
  • 41. private volatile long counter; private void nonAtomicOperation(){ counter++;} private void atomicOperation(){ counter = 281283;}
  • 42. Usage in double-checked pattern Java Memory Model permutes execution order in multi-thread world (JVM Specification) Visibility on flag_variable is mandatory to double-checked pattern volatile boolean flag_variable; //Assumed the type is boolean //Double-checked block
  • 43. Lock & Lock-free Lock Package java.util.concurrent.locks Lock-free Package java.util.concurrent.atomic
  • 45. Java Concurrency in Practice – Brian Goetz Java IO Java NIO