SlideShare una empresa de Scribd logo
1 de 31
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
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 PlatformMartin Zapletal
 
Network emulator
Network emulatorNetwork emulator
Network emulatorjeromy fu
 
Shared objects and synchronization
Shared objects and synchronization Shared objects and synchronization
Shared objects and synchronization Dr. C.V. Suresh Babu
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunningguest1f2740
 
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...antopensource
 
Linux Linux Traffic Control
Linux Linux Traffic ControlLinux Linux Traffic Control
Linux Linux Traffic ControlSUSE Labs Taipei
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with MicronautQAware GmbH
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 

La actualidad más candente (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
 

Destacado

Diary of a Scalable Java Application
Diary of a Scalable Java ApplicationDiary of a Scalable Java Application
Diary of a Scalable Java ApplicationMartin Jackson
 
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 CQL3Markus Klems
 
Java scalability considerations yogesh deshpande
Java scalability considerations   yogesh deshpandeJava scalability considerations   yogesh deshpande
Java scalability considerations yogesh deshpandeIndicThreads
 
Scalable Java Application Development on AWS
Scalable Java Application Development on AWSScalable Java Application Development on AWS
Scalable Java Application Development on AWSMikalai Alimenkou
 
Web20expo Scalable Web Arch
Web20expo Scalable Web ArchWeb20expo Scalable Web Arch
Web20expo Scalable Web Archmclee
 
Cuestionario internet Hernandez Michel
Cuestionario internet Hernandez MichelCuestionario internet Hernandez Michel
Cuestionario internet Hernandez Micheljhonzmichelle
 
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...Jerry SILVER
 
Scalable Application Development on AWS
Scalable Application Development on AWSScalable Application Development on AWS
Scalable Application Development on AWSMikalai Alimenkou
 
Scalable Applications with Scala
Scalable Applications with ScalaScalable Applications with Scala
Scalable Applications with ScalaNimrod Argov
 
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 S313978David Chou
 
Writing Scalable Software in Java
Writing Scalable Software in JavaWriting Scalable Software in Java
Writing Scalable Software in JavaRuben Badaró
 
Scalable Web Architectures and Infrastructure
Scalable Web Architectures and InfrastructureScalable Web Architectures and Infrastructure
Scalable Web Architectures and Infrastructuregeorge.james
 
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 usersAmazon Web Services
 
天猫后端技术架构优化实践
天猫后端技术架构优化实践天猫后端技术架构优化实践
天猫后端技术架构优化实践drewz lin
 
Building Web Scale Applications with AWS
Building Web Scale Applications with AWSBuilding Web Scale Applications with AWS
Building Web Scale Applications with AWSAmazon Web Services
 
Full stack-development with node js
Full stack-development with node jsFull stack-development with node js
Full stack-development with node jsXuefeng Zhang
 
Scalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed SystemsScalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed Systemshyun soomyung
 
浅谈电商网站数据访问层(DAL)与 ORM 之适用性
浅谈电商网站数据访问层(DAL)与 ORM 之适用性浅谈电商网站数据访问层(DAL)与 ORM 之适用性
浅谈电商网站数据访问层(DAL)与 ORM 之适用性Xuefeng Zhang
 
Machine learning with scikitlearn
Machine learning with scikitlearnMachine learning with scikitlearn
Machine learning with scikitlearnPratap Dangeti
 

Destacado (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
 

Similar a Highly Scalable Java Programming for Multi-Core System

Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
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)Sneeker Yeh
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
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 20111108Mathias Herberts
 
Architecting for Microservices Part 2
Architecting for Microservices Part 2Architecting for Microservices Part 2
Architecting for Microservices Part 2Elana Krasner
 
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 ...Takuo Watanabe
 
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.1Hajime Tazaki
 
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 BorgersNLJUG
 
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 ScaleSean Zhong
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
NetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talksNetflixOSS Open House Lightning talks
NetflixOSS Open House Lightning talksRuslan Meshenberg
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded ProgrammingAdil Jafri
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
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 ClusterKonstantin Tsykulenko
 
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 LanguageAsankhaya Sharma
 
Load Balancing In Cloud Computing newppt
Load Balancing In Cloud Computing newpptLoad Balancing In Cloud Computing newppt
Load Balancing In Cloud Computing newpptUtshab Saha
 
Concurrency (Fisher Syer S2GX 2010)
Concurrency (Fisher Syer S2GX 2010)Concurrency (Fisher Syer S2GX 2010)
Concurrency (Fisher Syer S2GX 2010)Dave Syer
 
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 StackKeitaSugiyama1
 

Similar 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

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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...apidays
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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 DiscoveryTrustArc
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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...DianaGray10
 
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 TerraformAndrey Devyatkin
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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 Takeoffsammart93
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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...
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

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 del 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 