[go: up one dir, main page]

SlideShare a Scribd company logo
Writing Scalable
Software in Java
From multi-core to grid-computing
Me

•   Ruben Badaró
•   Dev Expert at Changingworlds/Amdocs
•   PT.JUG Leader
•   http://www.zonaj.org
What this talk is not
       about
• Sales pitch
• Cloud Computing
• Service Oriented Architectures
• Java EE
• How to write multi-threaded code
Summary

• Define Performance and Scalability
• Vertical Scalability - scaling up
• Horizontal Scalability - scaling out
• Q&A
Performance != Scalability
Performance


 Amount of useful work accomplished by a
computer system compared to the time and
             resources used
Scalability


Capability of a system to increase the amount of
useful work as resources and load are added to
                    the system
Scalability

•   A system that performs fast with 10 users
    might not do so with 1000 - it doesn’t scale
•   Designing for scalability always decreases
    performance
Linear Scalability
Throughput




                          Resources
Reality is sub-linear
Throughput




                     Resources
Amdahl’s Law
Scalability is about
       parallelizing
• Parallel decomposition allows division of
  work
• Parallelizing might mean more work
• There’s almost always a part of serial
  computation
Vertical Scalability
Vertical Scalability
      Somewhat hard
Vertical Scalability
                      Scale Up

•   Bigger, meaner machines
    -   More cores (and more powerful)
    -   More memory
    -   Faster local storage
•   Limited
    -   Technical constraints
    -   Cost - big machines get exponentially
        expensive
Shared State

• Need to use those cores
• Java - shared-state concurrency
 - Mutable state protected with locks
 - Hard to get right
 - Most developers don’t have experience
    writing multithreaded code
This is how they look
              like
public static synchronized SomeObject getInstance() {

    return instance;

}



public SomeObject doConcurrentThingy() {

    synchronized(this) {

        //...

    }

    return ..;

}
Single vs Multi-threaded
 •   Single-threaded

     -   No scheduling cost
     -   No synchronization cost
 •   Multi-threaded
     -   Context Switching (high cost)
     -   Memory Synchronization (memory barriers)
     -   Blocking
Lock Contention
             Little’s Law


The average number of customers in a stable
 system is equal to their average arrival rate
multiplied by their average time in the system
Reducing Contention
•   Reduce lock duration
•   Reduce frequency with which locks are
    requested (stripping)
•   Replace exclusive locks with other mechanisms
    -   Concurrent Collections
    -   ReadWriteLocks
    -   Atomic Variables
    -   Immutable Objects
Concurrent Collections

 • Use lock stripping
 • Includes    putIfAbsent()   and replace()
     methods
 •   ConcurrentHashMap   has 16 separate locks by
     default
 • Don’t reinvent the wheel
ReadWriteLocks

• Pair of locks
• Read lock can be held by multiple
  threads if there are no writers
• Write lock is exclusive
• Good improvements if object as fewer
  writers
Atomic Variables

• Allow to make check-update type of
  operations atomically
• Without locks - use low-level CPU
  instructions
• It’s   volatile   on steroids (visibility +
  atomicity)
Immutable Objects
•   Immutability makes concurrency simple - thread-
    safety guaranteed
•   An immutable object is:
    - final
    -   fields are final and private
    -   Constructor constructs the object completely
    -   No state changing methods
    -   Copy internal mutable objects when receiving
        or returning
JVM issues
•   Caching is useful - storing stuff in memory
•   Larger JVM heap size means longer garbage
    collection times
•   Not acceptable to have long pauses
•   Solutions
    -   Maximum size for heap 2GB/4GB
    -   Multiple JVMs per machine
    -   Better garbage collectors: G1 might help
Scaling Up: Other
        Approaches
• Change the paradigm
 - Actors (Erlang and Scala)
 - Dataflow programming (GParallelizer)
 - Software Transactional Memory
     (Pastrami)
 -   Functional languages, such as Clojure
Scaling Up: Other
        Approaches
• Dedicated JVM-friendly hardware
 - Azul Systems is amazing
 - Hundreds of cores
 - Enormous heap sizes with negligible gc
     pauses
 -   HTM included
 -   Built-in lock elision mechanism
Horizontal Scalability
Horizontal Scalability
       The hard part
Horizontal Scalability
               Scale Out


• Big machines are expensive - 1 x 32 core
  normally much more expensive than 4 x
  8 core
• Increase throughput by adding more
  machines
• Distributed Systems research revisited -
  not new
Requirements

• Scalability
• Availability
• Reliability
• Performance
Typical Server Architecture
... # of users increases
... and increases
... too much load
... and we loose availability
... so we add servers
... and a load balancer
... and another one rides the bus
... we create a DB cluster
... and we cache wherever we can



              Cache




              Cache
Challenges

• How do we route requests to servers?
• How do distribute data between servers?
• How do we handle failures?
• How do we keep our cache consistent?
• How do we handle load peaks?
Technique #1: Partitioning



  A     F      K      P     U
  ...   ...    ...    ...   ...
  E      J     O      T     Z

              Users
Technique #1: Partitioning

  • Each server handles a subset of data
  • Improves scalability by parallelizing
  • Requires predictable routing
  • Introduces problems with locality
  • Move work to where the data is!
Technique #2: Replication

Active




Backup
Technique #2: Replication

  • Keep copies of data/state in multiple
    servers
  • Used for fail-over - increases availability
  • Requires more cold hardware
  • Overhead of replicating might reduce
    performance
Technique #3: Messaging
Technique #3: Messaging
 • Use message passing, queues and pub/sub
   models - JMS
 • Improves reliability easily
 • Helps deal with peaks
  - The queue keeps filling
  - If it gets too big, extra requests are
     rejected
Solution #1: De-
      normalize DB
• Faster queries
• Additional work to generate tables
• Less space efficiency
• Harder to maintain consistency
Solution #2: Non-SQL
       Database

• Why not remove the relational part
  altogether
• Bad for complex queries
• Berkeley DB is a prime example
Solution #3: Distributed
       Key/Value Stores
•   Highly scalable - used in the largest websites in the
    world, based on Amazon’s Dynamo and Google’s
    BigTable
•   Mostly open source
•   Partitioned
•   Replicated
•   Versioned
•   No SPOF
•   Voldemort (LinkedIn), Cassandra (Facebook) and HBase
    are written in Java
Solution #4:
MapReduce




    Map...
Solution #4:
MapReduce




    Map...
Solution #4:
MapReduce


               Divide Work




    Map...
Solution #4:
MapReduce


               Divide Work




    Map...
Solution #4:
MapReduce


               Divide Work




    Map...
Solution #4:
MapReduce




    Map...
Solution #4:
MapReduce


               Compute




    Map...
Solution #4:
MapReduce

               Return and
                aggregate




   Reduce...
Solution #4:
MapReduce

               Return and
                aggregate




   Reduce...
Solution #4:
MapReduce

               Return and
                aggregate




   Reduce...
Solution #4:
          MapReduce
• Google’s algorithm to split work, process it
  and reduce to an answer
• Used for offline processing of large
  amounts of data
• Hadoop is used everywhere! Other options
  such as GridGain exist
Solution #5: Data Grid
• Data (and computations)
• In-memory - low response times
• Database back-end (SQL or not)
• Partitioned - operations on data executed in
  specific partition
• Replicated - handles failover automatically
• Transactional
Solution #5: Data Grid
• It’s a distributed cache + computational
  engine
• Can be used as a cache with JPA and the like
• Oracle Coherence is very good.
• Terracotta, Gridgain, Gemfire, Gigaspaces,
  Velocity (Microsoft) and Websphere
  extreme scale (IBM)
Retrospective

• You need to scale up and out
• Write code thinking of hundreds of cores
• Relational might not be the way to go
• Cache whenever you can
• Be aware of data locality
Q &A
Thanks for listening!




                       Ruben Badaró
                http://www.zonaj.org

More Related Content

What's hot

Kafka replication apachecon_2013
Kafka replication apachecon_2013Kafka replication apachecon_2013
Kafka replication apachecon_2013
Jun Rao
 

What's hot (20)

Scalability, Availability & Stability Patterns
Scalability, Availability & Stability PatternsScalability, Availability & Stability Patterns
Scalability, Availability & Stability Patterns
 
Stability Patterns for Microservices
Stability Patterns for MicroservicesStability Patterns for Microservices
Stability Patterns for Microservices
 
Grokking Techtalk #39: Gossip protocol and applications
Grokking Techtalk #39: Gossip protocol and applicationsGrokking Techtalk #39: Gossip protocol and applications
Grokking Techtalk #39: Gossip protocol and applications
 
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
 
Thousands of Threads and Blocking I/O
Thousands of Threads and Blocking I/OThousands of Threads and Blocking I/O
Thousands of Threads and Blocking I/O
 
Greenplum and Kafka: Real-time Streaming to Greenplum - Greenplum Summit 2019
Greenplum and Kafka: Real-time Streaming to Greenplum - Greenplum Summit 2019Greenplum and Kafka: Real-time Streaming to Greenplum - Greenplum Summit 2019
Greenplum and Kafka: Real-time Streaming to Greenplum - Greenplum Summit 2019
 
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...
 
kafka
kafkakafka
kafka
 
Cassandra Introduction & Features
Cassandra Introduction & FeaturesCassandra Introduction & Features
Cassandra Introduction & Features
 
Redis Overview
Redis OverviewRedis Overview
Redis Overview
 
CAP theorem and distributed systems
CAP theorem and distributed systemsCAP theorem and distributed systems
CAP theorem and distributed systems
 
HazelCast
HazelCastHazelCast
HazelCast
 
Getting Started with Confluent Schema Registry
Getting Started with Confluent Schema RegistryGetting Started with Confluent Schema Registry
Getting Started with Confluent Schema Registry
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
RabbitMQ
RabbitMQRabbitMQ
RabbitMQ
 
Key-Value NoSQL Database
Key-Value NoSQL DatabaseKey-Value NoSQL Database
Key-Value NoSQL Database
 
Kafka replication apachecon_2013
Kafka replication apachecon_2013Kafka replication apachecon_2013
Kafka replication apachecon_2013
 
Redis vs Infinispan | DevNation Tech Talk
Redis vs Infinispan | DevNation Tech TalkRedis vs Infinispan | DevNation Tech Talk
Redis vs Infinispan | DevNation Tech Talk
 
Thrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonThrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased Comparison
 
Facebook Messages & HBase
Facebook Messages & HBaseFacebook Messages & HBase
Facebook Messages & HBase
 

Viewers also liked

MapReduce Debates and Schema-Free
MapReduce Debates and Schema-FreeMapReduce Debates and Schema-Free
MapReduce Debates and Schema-Free
hybrid cloud
 
Optimizing your java applications for multi core hardware
Optimizing your java applications for multi core hardwareOptimizing your java applications for multi core hardware
Optimizing your java applications for multi core hardware
IndicThreads
 
Securing Java EE Web Apps
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web Apps
Frank Kim
 
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
 

Viewers also liked (20)

MapReduce Debates and Schema-Free
MapReduce Debates and Schema-FreeMapReduce Debates and Schema-Free
MapReduce Debates and Schema-Free
 
Java tips
Java tipsJava tips
Java tips
 
Optimizing your java applications for multi core hardware
Optimizing your java applications for multi core hardwareOptimizing your java applications for multi core hardware
Optimizing your java applications for multi core hardware
 
Os
OsOs
Os
 
Operations-Driven Web Services at Rent the Runway
Operations-Driven Web Services at Rent the RunwayOperations-Driven Web Services at Rent the Runway
Operations-Driven Web Services at Rent the Runway
 
Securing Java EE Web Apps
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web Apps
 
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
 
Scalable Application Development on AWS
Scalable Application Development on AWSScalable Application Development on AWS
Scalable Application Development on AWS
 
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...
 
Highly Scalable Java Programming for Multi-Core System
Highly Scalable Java Programming for Multi-Core SystemHighly Scalable Java Programming for Multi-Core System
Highly Scalable Java Programming for Multi-Core System
 
Scalable Applications with Scala
Scalable Applications with ScalaScalable Applications with Scala
Scalable Applications with Scala
 
Intro to Erlang
Intro to ErlangIntro to Erlang
Intro to Erlang
 
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
 
Diary of a Scalable Java Application
Diary of a Scalable Java ApplicationDiary of a Scalable Java Application
Diary of a Scalable Java Application
 
Java scalability considerations yogesh deshpande
Java scalability considerations   yogesh deshpandeJava scalability considerations   yogesh deshpande
Java scalability considerations yogesh deshpande
 
Scalable web architecture
Scalable web architectureScalable web architecture
Scalable web architecture
 
Scalable Java Application Development on AWS
Scalable Java Application Development on AWSScalable Java Application Development on AWS
Scalable Java Application Development on AWS
 
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
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 

Similar to Writing Scalable Software in Java

Big Data (NJ SQL Server User Group)
Big Data (NJ SQL Server User Group)Big Data (NJ SQL Server User Group)
Big Data (NJ SQL Server User Group)
Don Demcsak
 
Intro to Big Data and NoSQL
Intro to Big Data and NoSQLIntro to Big Data and NoSQL
Intro to Big Data and NoSQL
Don Demcsak
 

Similar to Writing Scalable Software in Java (20)

Jay Kreps on Project Voldemort Scaling Simple Storage At LinkedIn
Jay Kreps on Project Voldemort Scaling Simple Storage At LinkedInJay Kreps on Project Voldemort Scaling Simple Storage At LinkedIn
Jay Kreps on Project Voldemort Scaling Simple Storage At LinkedIn
 
Drupal performance
Drupal performanceDrupal performance
Drupal performance
 
ApacheCon2010: Cache & Concurrency Considerations in Cassandra (& limits of JVM)
ApacheCon2010: Cache & Concurrency Considerations in Cassandra (& limits of JVM)ApacheCon2010: Cache & Concurrency Considerations in Cassandra (& limits of JVM)
ApacheCon2010: Cache & Concurrency Considerations in Cassandra (& limits of JVM)
 
Big Data (NJ SQL Server User Group)
Big Data (NJ SQL Server User Group)Big Data (NJ SQL Server User Group)
Big Data (NJ SQL Server User Group)
 
Mtc learnings from isv & enterprise interaction
Mtc learnings from isv & enterprise  interactionMtc learnings from isv & enterprise  interaction
Mtc learnings from isv & enterprise interaction
 
Mtc learnings from isv & enterprise (dated - Dec -2014)
Mtc learnings from isv & enterprise (dated - Dec -2014)Mtc learnings from isv & enterprise (dated - Dec -2014)
Mtc learnings from isv & enterprise (dated - Dec -2014)
 
Hardware Provisioning
Hardware ProvisioningHardware Provisioning
Hardware Provisioning
 
Cloud computing UNIT 2.1 presentation in
Cloud computing UNIT 2.1 presentation inCloud computing UNIT 2.1 presentation in
Cloud computing UNIT 2.1 presentation in
 
Cloud infrastructure. Google File System and MapReduce - Andrii Vozniuk
Cloud infrastructure. Google File System and MapReduce - Andrii VozniukCloud infrastructure. Google File System and MapReduce - Andrii Vozniuk
Cloud infrastructure. Google File System and MapReduce - Andrii Vozniuk
 
Intro to Big Data and NoSQL
Intro to Big Data and NoSQLIntro to Big Data and NoSQL
Intro to Big Data and NoSQL
 
try
trytry
try
 
Eventual Consistency @WalmartLabs with Kafka, Avro, SolrCloud and Hadoop
Eventual Consistency @WalmartLabs with Kafka, Avro, SolrCloud and HadoopEventual Consistency @WalmartLabs with Kafka, Avro, SolrCloud and Hadoop
Eventual Consistency @WalmartLabs with Kafka, Avro, SolrCloud and Hadoop
 
Hadoop
HadoopHadoop
Hadoop
 
DrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalabilityDrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalability
 
Building Big Data Streaming Architectures
Building Big Data Streaming ArchitecturesBuilding Big Data Streaming Architectures
Building Big Data Streaming Architectures
 
August 2013 HUG: Removing the NameNode's memory limitation
August 2013 HUG: Removing the NameNode's memory limitation August 2013 HUG: Removing the NameNode's memory limitation
August 2013 HUG: Removing the NameNode's memory limitation
 
Development of concurrent services using In-Memory Data Grids
Development of concurrent services using In-Memory Data GridsDevelopment of concurrent services using In-Memory Data Grids
Development of concurrent services using In-Memory Data Grids
 
Dr and ha solutions with sql server azure
Dr and ha solutions with sql server azureDr and ha solutions with sql server azure
Dr and ha solutions with sql server azure
 
Distributed Computing with Apache Hadoop: Technology Overview
Distributed Computing with Apache Hadoop: Technology OverviewDistributed Computing with Apache Hadoop: Technology Overview
Distributed Computing with Apache Hadoop: Technology Overview
 
Graphene – Microsoft SCOPE on Tez
Graphene – Microsoft SCOPE on Tez Graphene – Microsoft SCOPE on Tez
Graphene – Microsoft SCOPE on Tez
 

Recently uploaded

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 

Recently uploaded (20)

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 

Writing Scalable Software in Java

  • 1. Writing Scalable Software in Java From multi-core to grid-computing
  • 2. Me • Ruben Badaró • Dev Expert at Changingworlds/Amdocs • PT.JUG Leader • http://www.zonaj.org
  • 3. What this talk is not about • Sales pitch • Cloud Computing • Service Oriented Architectures • Java EE • How to write multi-threaded code
  • 4. Summary • Define Performance and Scalability • Vertical Scalability - scaling up • Horizontal Scalability - scaling out • Q&A
  • 6. Performance Amount of useful work accomplished by a computer system compared to the time and resources used
  • 7. Scalability Capability of a system to increase the amount of useful work as resources and load are added to the system
  • 8. Scalability • A system that performs fast with 10 users might not do so with 1000 - it doesn’t scale • Designing for scalability always decreases performance
  • 12. Scalability is about parallelizing • Parallel decomposition allows division of work • Parallelizing might mean more work • There’s almost always a part of serial computation
  • 14. Vertical Scalability Somewhat hard
  • 15. Vertical Scalability Scale Up • Bigger, meaner machines - More cores (and more powerful) - More memory - Faster local storage • Limited - Technical constraints - Cost - big machines get exponentially expensive
  • 16. Shared State • Need to use those cores • Java - shared-state concurrency - Mutable state protected with locks - Hard to get right - Most developers don’t have experience writing multithreaded code
  • 17. This is how they look like public static synchronized SomeObject getInstance() { return instance; } public SomeObject doConcurrentThingy() { synchronized(this) { //... } return ..; }
  • 18. Single vs Multi-threaded • Single-threaded - No scheduling cost - No synchronization cost • Multi-threaded - Context Switching (high cost) - Memory Synchronization (memory barriers) - Blocking
  • 19. Lock Contention Little’s Law The average number of customers in a stable system is equal to their average arrival rate multiplied by their average time in the system
  • 20. Reducing Contention • Reduce lock duration • Reduce frequency with which locks are requested (stripping) • Replace exclusive locks with other mechanisms - Concurrent Collections - ReadWriteLocks - Atomic Variables - Immutable Objects
  • 21. Concurrent Collections • Use lock stripping • Includes putIfAbsent() and replace() methods • ConcurrentHashMap has 16 separate locks by default • Don’t reinvent the wheel
  • 22. ReadWriteLocks • Pair of locks • Read lock can be held by multiple threads if there are no writers • Write lock is exclusive • Good improvements if object as fewer writers
  • 23. Atomic Variables • Allow to make check-update type of operations atomically • Without locks - use low-level CPU instructions • It’s volatile on steroids (visibility + atomicity)
  • 24. Immutable Objects • Immutability makes concurrency simple - thread- safety guaranteed • An immutable object is: - final - fields are final and private - Constructor constructs the object completely - No state changing methods - Copy internal mutable objects when receiving or returning
  • 25. JVM issues • Caching is useful - storing stuff in memory • Larger JVM heap size means longer garbage collection times • Not acceptable to have long pauses • Solutions - Maximum size for heap 2GB/4GB - Multiple JVMs per machine - Better garbage collectors: G1 might help
  • 26. Scaling Up: Other Approaches • Change the paradigm - Actors (Erlang and Scala) - Dataflow programming (GParallelizer) - Software Transactional Memory (Pastrami) - Functional languages, such as Clojure
  • 27. Scaling Up: Other Approaches • Dedicated JVM-friendly hardware - Azul Systems is amazing - Hundreds of cores - Enormous heap sizes with negligible gc pauses - HTM included - Built-in lock elision mechanism
  • 29. Horizontal Scalability The hard part
  • 30. Horizontal Scalability Scale Out • Big machines are expensive - 1 x 32 core normally much more expensive than 4 x 8 core • Increase throughput by adding more machines • Distributed Systems research revisited - not new
  • 33. ... # of users increases
  • 35. ... too much load
  • 36. ... and we loose availability
  • 37. ... so we add servers
  • 38. ... and a load balancer
  • 39. ... and another one rides the bus
  • 40. ... we create a DB cluster
  • 41. ... and we cache wherever we can Cache Cache
  • 42. Challenges • How do we route requests to servers? • How do distribute data between servers? • How do we handle failures? • How do we keep our cache consistent? • How do we handle load peaks?
  • 43. Technique #1: Partitioning A F K P U ... ... ... ... ... E J O T Z Users
  • 44. Technique #1: Partitioning • Each server handles a subset of data • Improves scalability by parallelizing • Requires predictable routing • Introduces problems with locality • Move work to where the data is!
  • 46. Technique #2: Replication • Keep copies of data/state in multiple servers • Used for fail-over - increases availability • Requires more cold hardware • Overhead of replicating might reduce performance
  • 48. Technique #3: Messaging • Use message passing, queues and pub/sub models - JMS • Improves reliability easily • Helps deal with peaks - The queue keeps filling - If it gets too big, extra requests are rejected
  • 49. Solution #1: De- normalize DB • Faster queries • Additional work to generate tables • Less space efficiency • Harder to maintain consistency
  • 50. Solution #2: Non-SQL Database • Why not remove the relational part altogether • Bad for complex queries • Berkeley DB is a prime example
  • 51. Solution #3: Distributed Key/Value Stores • Highly scalable - used in the largest websites in the world, based on Amazon’s Dynamo and Google’s BigTable • Mostly open source • Partitioned • Replicated • Versioned • No SPOF • Voldemort (LinkedIn), Cassandra (Facebook) and HBase are written in Java
  • 54. Solution #4: MapReduce Divide Work Map...
  • 55. Solution #4: MapReduce Divide Work Map...
  • 56. Solution #4: MapReduce Divide Work Map...
  • 58. Solution #4: MapReduce Compute Map...
  • 59. Solution #4: MapReduce Return and aggregate Reduce...
  • 60. Solution #4: MapReduce Return and aggregate Reduce...
  • 61. Solution #4: MapReduce Return and aggregate Reduce...
  • 62. Solution #4: MapReduce • Google’s algorithm to split work, process it and reduce to an answer • Used for offline processing of large amounts of data • Hadoop is used everywhere! Other options such as GridGain exist
  • 63. Solution #5: Data Grid • Data (and computations) • In-memory - low response times • Database back-end (SQL or not) • Partitioned - operations on data executed in specific partition • Replicated - handles failover automatically • Transactional
  • 64. Solution #5: Data Grid • It’s a distributed cache + computational engine • Can be used as a cache with JPA and the like • Oracle Coherence is very good. • Terracotta, Gridgain, Gemfire, Gigaspaces, Velocity (Microsoft) and Websphere extreme scale (IBM)
  • 65. Retrospective • You need to scale up and out • Write code thinking of hundreds of cores • Relational might not be the way to go • Cache whenever you can • Be aware of data locality
  • 66. Q &A Thanks for listening! Ruben Badaró http://www.zonaj.org