SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
Highly Scalable Java Programming
      for Multi-Core System

        Zhi Gan (ganzhi@gmail.com)

        http://ganzhi.blogspot.com
Agenda

 • Software Challenges

 • Profiling Tools Introduction

 • Best Practice for Java Programming

 • Rocket Science: Lock-Free Programming




                            2
Software challenges
• Parallelism
   – Larger threads per system = more parallelism needed to achieve
     high utilization
   – Thread-to-thread affinity (shared code and/or data)

• Memory management
   – Sharing of cache and memory bandwidth across more threads =
     greater need for memory efficiency
   – Thread-to-memory affinity (execute thread closest to associated
     data)

• Storage management
   – Allocate data across DRAM, Disk & Flash according to access
     frequency and patterns

                                    3
Typical Scalability Curve
The 1st Step: Profiling Parallel
Application
Important Profiling Tools
• Java Lock Monitor (JLM)
  – understand the usage of locks in their applications
  – similar tool: Java Lock Analyzer (JLA)
• Multi-core SDK (MSDK)
  – in-depth analysis of the complete execution stack
• AIX Performance Tools
  – Simple Performance Lock Analysis Tool (SPLAT)
  – XProfiler
  – prof, tprof and gprof
Tprof and VPA tool
Java Lock Monitor



• %MISS : 100 * SLOW / NONREC
• GETS : Lock Entries
• NONREC : Non Recursive Gets
• SLOW : Non Recursives that Wait
• REC : Recursive Gets
• TIER2 : SMP: Total try-enter spin loop cnt (middle for 3
  tier)
• TIER3 : SMP: Total yield spin loop cnt (outer for 3 tier)
• %UTIL : 100 * Hold-Time / Total-Time
• AVER-HTM : Hold-Time / NONREC
Multi-core SDK
                              Dead Lock View




       Synchronization View
Best Practice for High Scalable Java
            Programming
What Is Lock Contention?




                           From JLM tool website
Lock Operation Itself Is Expensive
• CAS operations are predominantly used for
  locking
• it takes up a big part of the execution time
Reduce Locking Scope
public synchronized void foo1(int k)    public void foo2(int k) {
  {                                       String key =
    String key = Integer.toString(k);     Integer.toString(k);
    String value = key+"value";           String value = key+"value";
    if (null == key){                     if (null == key){
        return ;                                return ;
    }else {                               }else{
        maph.put(key, value);                   synchronized(this){
    }                                               maph.put(key, value);
}                                               }
                                          }
                                        }
                                                                     25%

Execution Time: 16106                   Execution Time: 12157
  milliseconds                            milliseconds
Results from JLM report




                          Reduced AVER_HTM
Lock Splitting
 public synchronized void   public void addUser2(String u){
   addUser1(String u) {       synchronized(users){
   users.add(u);                    users.add(u);
 }                            }
                            }
                            public void addQuery2(String q){
 public synchronized void     synchronized(queries){
   addQuery1(String q) {            queries.add(q);
   queries.add(q);            }
 }                          }

 Execution Time: 12981      Execution Time: 4797 milliseconds
   milliseconds
                                              64%
Result from JLM report




                         Reduced lock tries
Lock Striping
 public synchronized void       public void put2(int indx,
   put1(int indx, String k) {     String k) {
     share[indx] = k;             synchronized
 }                                (locks[indx%N_LOCKS]) {
                                       share[indx] = k;
                                   }
                                }

 Execution Time: 5536           Execution Time: 1857
   milliseconds                   milliseconds

                                              66%
Result from JLM report




                         More locks with
                         less AVER_HTM
Split Hot Points : Scalable Counter




  – ConcurrentHashMap maintains a independent
    counter for each segment of hash map, and use
    a lock for each counter
  – get global counter by sum all independent
    counters
Alternatives of Exclusive Lock
• Duplicate shared resource if possible
• Atomic variables
  – counter, sequential number generator, head
    pointer of linked-list
• Concurrent container
  – java.util.concurrent package, Amino lib
• Read-Write Lock
  – java.util.concurrent.locks.ReadWriteLock
Example of AtomicLongArray
public synchronized void set1(int   private final AtomicLongArray a;
  idx, long val) {
  d[idx] = val;                     public void set2(int idx, long val) {
}                                     a.addAndGet(idx, val);
                                    }

public synchronized long get1(int   public long get2(int idx) {
  idx) {                              long ret = a.get(idx); return ret;
  long ret = d[idx];                }
  return ret;
}

Execution Time: 23550               Execution Time: 842 milliseconds
  milliseconds
                                                   96%
Using Concurrent Container
• java.util.concurrent package
  – since Java1.5
  – ConcurrentHashMap, ConcurrentLinkedQueue,
    CopyOnWriteArrayList, etc
• Amino Lib is another good choice
  – LockFreeList, LockFreeStack, LockFreeQueue, etc
• Thread-safe container
• Optimized for common operations
• High performance and scalability for multi-core
  platform
• Drawback: without full feature support
Using Immutable and Thread Local data
• Immutable data
  – remain unchanged in its life cycle
  – always thread-safe
• Thread Local data
  – only be used by a single thread
  – not shared among different threads
  – to replace global waiting queue, object pool
  – used in work-stealing scheduler
Reduce Memory Allocation
• JVM: Two level of memory allocation
  – firstly from thread-local buffer
  – then from global buffer
• Thread-local buffer will be exhausted quickly
  if frequency of allocation is high
• ThreadLocal class may be helpful if
  temporary object is needed in a loop
Rocket Science: Lock-Free Programming
Using Lock-Free/Wait-Free Algorithm
• Lock-Free allow concurrent updates of
  shared data structures without using any
  locking mechanisms
  – solves some of the basic problems associated
    with using locks in the code
  – helps create algorithms that show good
    scalability
• Highly scalable and efficient
• Amino Lib
Why Lock-Free Often Means Better Scalability? (I)




  Lock:All threads wait for one
                               Lock free: No wait, but only one can succeed,
                                        Other threads need retry
Why Lock-Free Often Means Better Scalability? (II)




     X                                  X




  Lock:All threads wait for one
                               Lock free: No wait, but only one can succeed,
                                    Other threads often need to retry
Performance of A Lock-Free Stack




  Picture from: http://www.infoq.com/articles/scalable-java-components
References
• Amino Lib
  – http://amino-cbbs.sourceforge.net/
• MSDK
  – http://www.alphaworks.ibm.com/tech/msdk
• JLA
  – http://www.alphaworks.ibm.com/tech/jla
Backup

Mais conteúdo relacionado

Mais procurados

Network emulator
Network emulatorNetwork emulator
Network emulator
jeromy fu
 
Shared objects and synchronization
Shared objects and synchronization Shared objects and synchronization
Shared objects and synchronization
Dr. C.V. Suresh Babu
 

Mais procurados (20)

Jvm memory model
Jvm memory modelJvm memory model
Jvm memory model
 
Apache Storm
Apache StormApache Storm
Apache Storm
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Large volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformLarge volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive Platform
 
Basanta jtr2009
Basanta jtr2009Basanta jtr2009
Basanta jtr2009
 
Network emulator
Network emulatorNetwork emulator
Network emulator
 
Shared objects and synchronization
Shared objects and synchronization Shared objects and synchronization
Shared objects and synchronization
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
 
2011.jtr.pbasanta.
2011.jtr.pbasanta.2011.jtr.pbasanta.
2011.jtr.pbasanta.
 
Tc basics
Tc basicsTc basics
Tc basics
 
Isola 12 presentation
Isola 12 presentationIsola 12 presentation
Isola 12 presentation
 
From Trill to Quill and Beyond
From Trill to Quill and BeyondFrom Trill to Quill and Beyond
From Trill to Quill and Beyond
 
WWX14 speech : Justin Donaldson "Promhx : Cross-platform Promises and Reactiv...
WWX14 speech : Justin Donaldson "Promhx : Cross-platform Promises and Reactiv...WWX14 speech : Justin Donaldson "Promhx : Cross-platform Promises and Reactiv...
WWX14 speech : Justin Donaldson "Promhx : Cross-platform Promises and Reactiv...
 
No Heap Remote Objects for Distributed real-time Java
No Heap Remote Objects for Distributed real-time JavaNo Heap Remote Objects for Distributed real-time Java
No Heap Remote Objects for Distributed real-time Java
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 
Quantum programming
Quantum programmingQuantum programming
Quantum programming
 
Linux Linux Traffic Control
Linux Linux Traffic ControlLinux Linux Traffic Control
Linux Linux Traffic Control
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with Micronaut
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Thanos - Prometheus on Scale
Thanos - Prometheus on ScaleThanos - Prometheus on Scale
Thanos - Prometheus on Scale
 

Destaque

Cuestionario internet Hernandez Michel
Cuestionario internet Hernandez MichelCuestionario internet Hernandez Michel
Cuestionario internet Hernandez Michel
jhonzmichelle
 
Scalable Applications with Scala
Scalable Applications with ScalaScalable Applications with Scala
Scalable Applications with Scala
Nimrod Argov
 
Scalable Web Architectures and Infrastructure
Scalable Web Architectures and InfrastructureScalable Web Architectures and Infrastructure
Scalable Web Architectures and Infrastructure
george.james
 
天猫后端技术架构优化实践
天猫后端技术架构优化实践天猫后端技术架构优化实践
天猫后端技术架构优化实践
drewz lin
 

Destaque (20)

Diary of a Scalable Java Application
Diary of a Scalable Java ApplicationDiary of a Scalable Java Application
Diary of a Scalable Java Application
 
Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3Apache Cassandra Lesson: Data Modelling and CQL3
Apache Cassandra Lesson: Data Modelling and CQL3
 
Java scalability considerations yogesh deshpande
Java scalability considerations   yogesh deshpandeJava scalability considerations   yogesh deshpande
Java scalability considerations yogesh deshpande
 
Scalable Java Application Development on AWS
Scalable Java Application Development on AWSScalable Java Application Development on AWS
Scalable Java Application Development on AWS
 
Web20expo Scalable Web Arch
Web20expo Scalable Web ArchWeb20expo Scalable Web Arch
Web20expo Scalable Web Arch
 
Cuestionario internet Hernandez Michel
Cuestionario internet Hernandez MichelCuestionario internet Hernandez Michel
Cuestionario internet Hernandez Michel
 
Building a Scalable XML-based Dynamic Delivery Architecture: Standards and Be...
Building a Scalable XML-based Dynamic Delivery Architecture: Standards and Be...Building a Scalable XML-based Dynamic Delivery Architecture: Standards and Be...
Building a Scalable XML-based Dynamic Delivery Architecture: Standards and Be...
 
Scalable Application Development on AWS
Scalable Application Development on AWSScalable Application Development on AWS
Scalable Application Development on AWS
 
Scalable Applications with Scala
Scalable Applications with ScalaScalable Applications with Scala
Scalable Applications with Scala
 
Building Highly Scalable Java Applications on Windows Azure - JavaOne S313978
Building Highly Scalable Java Applications on Windows Azure - JavaOne S313978Building Highly Scalable Java Applications on Windows Azure - JavaOne S313978
Building Highly Scalable Java Applications on Windows Azure - JavaOne S313978
 
Writing Scalable Software in Java
Writing Scalable Software in JavaWriting Scalable Software in Java
Writing Scalable Software in Java
 
Scalable web architecture
Scalable web architectureScalable web architecture
Scalable web architecture
 
Scalable Web Architectures and Infrastructure
Scalable Web Architectures and InfrastructureScalable Web Architectures and Infrastructure
Scalable Web Architectures and Infrastructure
 
Building and Managing Scalable Applications on AWS: 1 to 500K users
Building and Managing Scalable Applications on AWS: 1 to 500K usersBuilding and Managing Scalable Applications on AWS: 1 to 500K users
Building and Managing Scalable Applications on AWS: 1 to 500K users
 
天猫后端技术架构优化实践
天猫后端技术架构优化实践天猫后端技术架构优化实践
天猫后端技术架构优化实践
 
Building Web Scale Applications with AWS
Building Web Scale Applications with AWSBuilding Web Scale Applications with AWS
Building Web Scale Applications with AWS
 
Full stack-development with node js
Full stack-development with node jsFull stack-development with node js
Full stack-development with node js
 
Scalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed SystemsScalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed Systems
 
浅谈电商网站数据访问层(DAL)与 ORM 之适用性
浅谈电商网站数据访问层(DAL)与 ORM 之适用性浅谈电商网站数据访问层(DAL)与 ORM 之适用性
浅谈电商网站数据访问层(DAL)与 ORM 之适用性
 
Machine learning with scikitlearn
Machine learning with scikitlearnMachine learning with scikitlearn
Machine learning with scikitlearn
 

Semelhante a Highly Scalable Java Programming for Multi-Core System

13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
Adil Jafri
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph Language
Asankhaya Sharma
 
Load Balancing In Cloud Computing newppt
Load Balancing In Cloud Computing newpptLoad Balancing In Cloud Computing newppt
Load Balancing In Cloud Computing newppt
Utshab Saha
 

Semelhante a Highly Scalable Java Programming for Multi-Core System (20)

Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Dead Lock Analysis of spin_lock() in Linux Kernel (english)
Dead Lock Analysis of spin_lock() in Linux Kernel (english)Dead Lock Analysis of spin_lock() in Linux Kernel (english)
Dead Lock Analysis of spin_lock() in Linux Kernel (english)
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108
 
Architecting for Microservices Part 2
Architecting for Microservices Part 2Architecting for Microservices Part 2
Architecting for Microservices Part 2
 
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
Towards an Integration of the Actor Model in an FRP Language for Small-Scale ...
 
Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
LibOS as a regression test framework for Linux networking #netdev1.1
LibOS as a regression test framework for Linux networking #netdev1.1LibOS as a regression test framework for Linux networking #netdev1.1
LibOS as a regression test framework for Linux networking #netdev1.1
 
Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen Borgers
 
Strata Singapore: Gearpump Real time DAG-Processing with Akka at Scale
Strata Singapore: GearpumpReal time DAG-Processing with Akka at ScaleStrata Singapore: GearpumpReal time DAG-Processing with Akka at Scale
Strata Singapore: Gearpump Real time DAG-Processing with Akka at Scale
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
NetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talksNetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talks
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph Language
 
Load Balancing In Cloud Computing newppt
Load Balancing In Cloud Computing newpptLoad Balancing In Cloud Computing newppt
Load Balancing In Cloud Computing newppt
 
Concurrency (Fisher Syer S2GX 2010)
Concurrency (Fisher Syer S2GX 2010)Concurrency (Fisher Syer S2GX 2010)
Concurrency (Fisher Syer S2GX 2010)
 
Grow and Shrink - Dynamically Extending the Ruby VM Stack
Grow and Shrink - Dynamically Extending the Ruby VM StackGrow and Shrink - Dynamically Extending the Ruby VM Stack
Grow and Shrink - Dynamically Extending the Ruby VM Stack
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Highly Scalable Java Programming for Multi-Core System

  • 1. Highly Scalable Java Programming for Multi-Core System Zhi Gan (ganzhi@gmail.com) http://ganzhi.blogspot.com
  • 2. Agenda • Software Challenges • Profiling Tools Introduction • Best Practice for Java Programming • Rocket Science: Lock-Free Programming 2
  • 3. Software challenges • Parallelism – Larger threads per system = more parallelism needed to achieve high utilization – Thread-to-thread affinity (shared code and/or data) • Memory management – Sharing of cache and memory bandwidth across more threads = greater need for memory efficiency – Thread-to-memory affinity (execute thread closest to associated data) • Storage management – Allocate data across DRAM, Disk & Flash according to access frequency and patterns 3
  • 5. The 1st Step: Profiling Parallel Application
  • 6. Important Profiling Tools • Java Lock Monitor (JLM) – understand the usage of locks in their applications – similar tool: Java Lock Analyzer (JLA) • Multi-core SDK (MSDK) – in-depth analysis of the complete execution stack • AIX Performance Tools – Simple Performance Lock Analysis Tool (SPLAT) – XProfiler – prof, tprof and gprof
  • 8. Java Lock Monitor • %MISS : 100 * SLOW / NONREC • GETS : Lock Entries • NONREC : Non Recursive Gets • SLOW : Non Recursives that Wait • REC : Recursive Gets • TIER2 : SMP: Total try-enter spin loop cnt (middle for 3 tier) • TIER3 : SMP: Total yield spin loop cnt (outer for 3 tier) • %UTIL : 100 * Hold-Time / Total-Time • AVER-HTM : Hold-Time / NONREC
  • 9. Multi-core SDK Dead Lock View Synchronization View
  • 10. Best Practice for High Scalable Java Programming
  • 11. What Is Lock Contention? From JLM tool website
  • 12. Lock Operation Itself Is Expensive • CAS operations are predominantly used for locking • it takes up a big part of the execution time
  • 13. Reduce Locking Scope public synchronized void foo1(int k) public void foo2(int k) { { String key = String key = Integer.toString(k); Integer.toString(k); String value = key+"value"; String value = key+"value"; if (null == key){ if (null == key){ return ; return ; }else { }else{ maph.put(key, value); synchronized(this){ } maph.put(key, value); } } } } 25% Execution Time: 16106 Execution Time: 12157 milliseconds milliseconds
  • 14. Results from JLM report Reduced AVER_HTM
  • 15. Lock Splitting public synchronized void public void addUser2(String u){ addUser1(String u) { synchronized(users){ users.add(u); users.add(u); } } } public void addQuery2(String q){ public synchronized void synchronized(queries){ addQuery1(String q) { queries.add(q); queries.add(q); } } } Execution Time: 12981 Execution Time: 4797 milliseconds milliseconds 64%
  • 16. Result from JLM report Reduced lock tries
  • 17. Lock Striping public synchronized void public void put2(int indx, put1(int indx, String k) { String k) { share[indx] = k; synchronized } (locks[indx%N_LOCKS]) { share[indx] = k; } } Execution Time: 5536 Execution Time: 1857 milliseconds milliseconds 66%
  • 18. Result from JLM report More locks with less AVER_HTM
  • 19. Split Hot Points : Scalable Counter – ConcurrentHashMap maintains a independent counter for each segment of hash map, and use a lock for each counter – get global counter by sum all independent counters
  • 20. Alternatives of Exclusive Lock • Duplicate shared resource if possible • Atomic variables – counter, sequential number generator, head pointer of linked-list • Concurrent container – java.util.concurrent package, Amino lib • Read-Write Lock – java.util.concurrent.locks.ReadWriteLock
  • 21. Example of AtomicLongArray public synchronized void set1(int private final AtomicLongArray a; idx, long val) { d[idx] = val; public void set2(int idx, long val) { } a.addAndGet(idx, val); } public synchronized long get1(int public long get2(int idx) { idx) { long ret = a.get(idx); return ret; long ret = d[idx]; } return ret; } Execution Time: 23550 Execution Time: 842 milliseconds milliseconds 96%
  • 22. Using Concurrent Container • java.util.concurrent package – since Java1.5 – ConcurrentHashMap, ConcurrentLinkedQueue, CopyOnWriteArrayList, etc • Amino Lib is another good choice – LockFreeList, LockFreeStack, LockFreeQueue, etc • Thread-safe container • Optimized for common operations • High performance and scalability for multi-core platform • Drawback: without full feature support
  • 23. Using Immutable and Thread Local data • Immutable data – remain unchanged in its life cycle – always thread-safe • Thread Local data – only be used by a single thread – not shared among different threads – to replace global waiting queue, object pool – used in work-stealing scheduler
  • 24. Reduce Memory Allocation • JVM: Two level of memory allocation – firstly from thread-local buffer – then from global buffer • Thread-local buffer will be exhausted quickly if frequency of allocation is high • ThreadLocal class may be helpful if temporary object is needed in a loop
  • 26. Using Lock-Free/Wait-Free Algorithm • Lock-Free allow concurrent updates of shared data structures without using any locking mechanisms – solves some of the basic problems associated with using locks in the code – helps create algorithms that show good scalability • Highly scalable and efficient • Amino Lib
  • 27. Why Lock-Free Often Means Better Scalability? (I) Lock:All threads wait for one Lock free: No wait, but only one can succeed, Other threads need retry
  • 28. Why Lock-Free Often Means Better Scalability? (II) X X Lock:All threads wait for one Lock free: No wait, but only one can succeed, Other threads often need to retry
  • 29. Performance of A Lock-Free Stack Picture from: http://www.infoq.com/articles/scalable-java-components
  • 30. References • Amino Lib – http://amino-cbbs.sourceforge.net/ • MSDK – http://www.alphaworks.ibm.com/tech/msdk • JLA – http://www.alphaworks.ibm.com/tech/jla

Notas do Editor

  1. What if all previous best prestise cannot meet your need? You would like to optimize your application manually?
  2. msdk – This tool can be used to do detailed performance analysis of concurrent Java applications. It does an in-depth analysis of the complete execution stack, starting from the hardware to the application layer. Information is gathered from all four layers of the stack – hardware, operating system, jvm and application.
  3. `
  4. For multi-thread application, lock-free approach is different with lock-based approach in several aspects: When accessing shared resource, lock-based approach will only allow one thread to enter critical section and others will wait for it On the contrary, lock-free approach will all every thread to modify state of shared state. But one of the all threads can succeed, and all other threads will be aware of their action are failed so they will retry or choose other actions.
  5. The real difference occurs when something bad happens to the running thread. If a running thread is paused by OS scheduler, different thing will happen to the two approach: Lock-based approach: All other threads are waiting for this thread, and no one can make progress Lock-free approach: Other threads will be free to do any operations. And the paused thread might fail its current operation From this difference, we can found in multi-core environment, lock-free will have more advantage. It will have better scalability since threads don’t wait for each other. And it will waste some CPU cycles if contention. But this won’t be a problem for most cases since we have more than enough CPU resource 