SlideShare a Scribd company logo
1 of 32
Java
Concurrency
By: Hithem Aly
Agenda
 Objective
 Facts
 ThreadSafety
 Java Concurrency Problems (Symptoms)
 Java Concurrency methods
Objective
 Managing   shared state
Objective
 Shared   State



                   Method
                    Area
Is That Thread Safe?
package com.thread;

class ApplicationThread implements Runnable{

     private int i = 0;

     @Override
     public void run() {
     System.out.println(++i);
     }
}

public class Main {

public static void main(String[] args) {

     for (int i = 0; i < 1000; i++)
     {
     Thread thread1 = new Thread(new ApplicationThread());
     thread1.start();
     }
     }
}
Is That Thread Safe?
package com.thread;

class ApplicationThread implements Runnable{

     private int i = 0;

     @Override
     public void run() {
     System.out.println(++i);
     }
}
public class Main {

     public static void main(String[] args) {

     Runnable runnable = new ApplicationThread();

     for (int i = 0; i < 100000; i++)
     {
     Thread thread1 = new Thread(runnable);
     thread1.start();
     }
     }
}
Agenda
 Objective
 Facts
 ThreadSafety
 Java Concurrency Problems (Symptoms)
 Java Concurrency methods
Facts
 Processors,cache, RAM interactions
 Compilers optimization (Instructions Re-
  ordering)
Processors, cache, RAM
   interactions
Thread 1

 Thread 2            P1              P2
                R1              R2


                     C1              C2




                                               text
   Stack    Stack
                          RAM        Heap    (code)
     1        2
                                            segment
Compilers optimization
• Constant folding

Ex:

static final int length = 25;
static final int width = 10;
int res = length * width; //int res = 250;


• Drop memory write for non volatile variables
• Instructions Reordering

•    int A, B;                   • int A, B;
•    void foo()                  • void foo()
•    { A = B + 1;                • {B = 0;
•    B = 0; }                    • A = B + 1; }

    For more Reference, Cglib (Code generation Library)
Illustrative Example
public class NoVisibility
{
    private static boolean ready;
    private static int number;

    private static class ReaderThread extends Thread
    {
           public void run()
           {
                       while (!ready)
                       Thread.yield();
                       System.out.println(number);
           }
    }


    public static void main(String[] args)
    {
          new ReaderThread().start();
          number = 42;
          ready = true;
    }
}
Solution
public class NoVisibility
{
    private static volatile boolean ready;
    private static volatile int number;

    private static class ReaderThread extends Thread
    {
           public void run()
           {
                       while (!ready)
                       Thread.yield();
                       System.out.println(number);
           }
    }


    public static void main(String[] args)
    {
          new ReaderThread().start();
          number = 42;
          ready = true;
    }
}
Agenda
 Objective
 Facts
 ThreadSafety
 Java Concurrency Problems (Symptoms)
 Java Concurrency methods
Singleton
Is That Thread Safe?
class Demo {

    private static Collaborator collaborator;

    public Collaborator getCollaborator() {
      if (collaborator == null) {
          collaborator = new Collaborator();
      }
      return collaborator;
    }
}
Thread Safety
                                   Atomicity     synchronized




                                  Concurrency




                                    Visibility     Volatile
Volatile Patterns
    • One thread writes Other Threads
       reads
    • Checking Status flags
    • Independent Observations
Thread Safe
class Demo {

    private static Collaborator collaborator;

    public synchronized Collaborator getCollaborator()
{
        if (collaborator == null) {
            collaborator = new Collaborator();
        }
        return collaborator;
    }
}
Optimized Solution
class Demo {

    private static volatile Collaborator collaborator;

    public Collaborator getCollaborator() {
      if (collaborator == null) {// double checked locking code
          synchronized(this) {
            if (collaborator == null) {
                collaborator = new Collaborator();
            }
          }
      }
      return collaborator;
    }
}
Even more Optimized
class Demo {

    private static volatile Collaborator collaborator;

    public Collaborator getCollaborator() {
      Collaborator tmp = collaborator;
      if (tmp == null) {
          synchronized(this) {
            if (tmp == null) {
                tmp = new Collaborator();
                collaborator = tmp;
            }
          }
      }
      return tmp;
    }
}
Agenda
 Objective
 Facts
 ThreadSafety
 Java Concurrency Problems (Symptoms)
 Java Concurrency methods
Java Concurrency Problems
and Symptoms
   Invalid States
       Stale values (old values, other threads values)
       Null pointer exceptions
       Array out of bound exceptions

   Symptom
       Code works in Debugging while not working in the
        running mode or production mode
       Working with JVM vendor while not working with
        other
       Working with certain usage load and doesn’t work
        when the usage is increased (JIT Compiler)
Agenda
 Objective
 Facts
 ThreadSafety
 Java Concurrency Problems (Symptoms)
 Java Concurrency methods
Java Concurrency methods

 Thread    Confinement
 Stack Confinement
 Immutable
 Visibility
 Atomicity
Thread confinement
(Not to share)
   If data is only accessed from a single
    thread, no synchronization is needed.

   JDBC Connections , confines the connection
    for a single thread

   Implementation using ThreadLocal
Thread Confinement
public class ConnectionDispenser {

private static class ThreadLocalConnection extends ThreadLocal {
   public Object initialValue() {
     return DriverManager.
                   getConnection(ConfigurationSingleton.getDbUrl());
   }
 }

 private static ThreadLocalConnection conn = new
ThreadLocalConnection();

    public static Connection getConnection() {
      return (Connection) conn.get();
    }
}
Stack Confinement
   Not to share
     Object    can only reached using local
        variables.

     Widely           used in our projects
public class Income extends HttpServlet {


            @override
            protected void doPost(HttpServletRequest request, HttpServletResponse response) {


                        try
                        {
                                     IncomeForm income = Util.jsonToObject(input, IncomeForm.class);
Immutable
 Fieldsare Final , values are set only from
  the constructors, (this reference does not
  escaped)

 Immutable  V effectively Immutable (Fields
  are not declared final, but there are not
  setters methods )

 Volatile   Reference to Immutable Objects
Illustrative example
@Immutable
class OneValueCache {
  private final BigInteger lastNumber;
  private final BigInteger[] lastFactors;

    public OneValueCache(BigInteger i,
                BigInteger[] factors) {
      lastNumber = i;
      lastFactors = Arrays.copyOf(factors, factors.length);
    }

    public BigInteger[] getFactors(BigInteger i) {
      if (lastNumber == null !lastNumber.equals(i))
          return null;
      else
          return Arrays.copyOf(lastFactors, lastFactors.length);
    }
}
Using volatile to publish
immutable objects
 @ThreadSafe
 public class VolatileCachedFactorizer implements Servlet {
   private volatile OneValueCache cache =
      new OneValueCache(null, null);

     public void service(ServletRequest req, ServletResponse resp) {
       BigInteger i = extractFromRequest(req);
       BigInteger[] factors = cache.getFactors(i); //Tip !!!
       if (factors == null) {
           factors = factor(i);
           cache = new OneValueCache(i, factors);
       }
       encodeIntoResponse(resp, factors);
     }
 }
Volatile
volatile boolean shutdownRequested;

...

public void shutdown() {
shutdownRequested = true; }

public void doWork() {
  while (!shutdownRequested) {
    // do stuff
  }
}
Synchronized
class SynchronizedCounter {
  private int c = 0;

    public synchronized void increment() {
      c++;
    }

    public synchronized void decrement() {
      c--;
    }

    public synchronized int value() {
      return c;
    }

}
Agenda
 Objective
 Facts
 ThreadSafety
 Java Concurrency Problems (Symptoms)
 Java Concurrency methods
References
 Java    Concurrency in Practice
 https://www.student.cs.uwaterloo.ca/~cs
  350/W11/notes/threads.pdf
 http://antrix.net/posts/2012/java-lazy-
  initialization/?c=1276

More Related Content

What's hot

Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals ThreadsNeera Mital
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfacekeval_thummar
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Roman Elizarov
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in JavaMudit Gupta
 
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01Jérôme Rocheteau
 
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...Frank Nielsen
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMax Kleiner
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 

What's hot (20)

Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Core java
Core javaCore java
Core java
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
 
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 5) A Concise and Practical Introduction to Programming Algorithms in...
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 

Similar to Java concurrency

Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance TuningMinh Hoang
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHoward Lewis Ship
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataGPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataCodemotion Tel Aviv
 
Java session13
Java session13Java session13
Java session13Niit Care
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartGabriele Lana
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javacAnna Brzezińska
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 

Similar to Java concurrency (20)

Forgive me for i have allocated
Forgive me for i have allocatedForgive me for i have allocated
Forgive me for i have allocated
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Exploring lambdas and invokedynamic for embedded systems
Exploring lambdas and invokedynamic for embedded systemsExploring lambdas and invokedynamic for embedded systems
Exploring lambdas and invokedynamic for embedded systems
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for JavaHave Your Cake and Eat It Too: Meta-Programming Techniques for Java
Have Your Cake and Eat It Too: Meta-Programming Techniques for Java
 
Thread
ThreadThread
Thread
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaDataGPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
GPARS: Lessons from the parallel universe - Itamar Tayer, CoolaData
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
Java session13
Java session13Java session13
Java session13
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
core java
core javacore java
core java
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

Java concurrency

  • 2. Agenda  Objective  Facts  ThreadSafety  Java Concurrency Problems (Symptoms)  Java Concurrency methods
  • 3. Objective  Managing shared state
  • 4. Objective  Shared State Method Area
  • 5. Is That Thread Safe? package com.thread; class ApplicationThread implements Runnable{ private int i = 0; @Override public void run() { System.out.println(++i); } } public class Main { public static void main(String[] args) { for (int i = 0; i < 1000; i++) { Thread thread1 = new Thread(new ApplicationThread()); thread1.start(); } } }
  • 6. Is That Thread Safe? package com.thread; class ApplicationThread implements Runnable{ private int i = 0; @Override public void run() { System.out.println(++i); } } public class Main { public static void main(String[] args) { Runnable runnable = new ApplicationThread(); for (int i = 0; i < 100000; i++) { Thread thread1 = new Thread(runnable); thread1.start(); } } }
  • 7. Agenda  Objective  Facts  ThreadSafety  Java Concurrency Problems (Symptoms)  Java Concurrency methods
  • 8. Facts  Processors,cache, RAM interactions  Compilers optimization (Instructions Re- ordering)
  • 9. Processors, cache, RAM interactions Thread 1 Thread 2 P1 P2 R1 R2 C1 C2 text Stack Stack RAM Heap (code) 1 2 segment
  • 10. Compilers optimization • Constant folding Ex: static final int length = 25; static final int width = 10; int res = length * width; //int res = 250; • Drop memory write for non volatile variables • Instructions Reordering • int A, B; • int A, B; • void foo() • void foo() • { A = B + 1; • {B = 0; • B = 0; } • A = B + 1; } For more Reference, Cglib (Code generation Library)
  • 11. Illustrative Example public class NoVisibility { private static boolean ready; private static int number; private static class ReaderThread extends Thread { public void run() { while (!ready) Thread.yield(); System.out.println(number); } } public static void main(String[] args) { new ReaderThread().start(); number = 42; ready = true; } }
  • 12. Solution public class NoVisibility { private static volatile boolean ready; private static volatile int number; private static class ReaderThread extends Thread { public void run() { while (!ready) Thread.yield(); System.out.println(number); } } public static void main(String[] args) { new ReaderThread().start(); number = 42; ready = true; } }
  • 13. Agenda  Objective  Facts  ThreadSafety  Java Concurrency Problems (Symptoms)  Java Concurrency methods
  • 14. Singleton Is That Thread Safe? class Demo { private static Collaborator collaborator; public Collaborator getCollaborator() { if (collaborator == null) { collaborator = new Collaborator(); } return collaborator; } }
  • 15. Thread Safety Atomicity synchronized Concurrency Visibility Volatile Volatile Patterns • One thread writes Other Threads reads • Checking Status flags • Independent Observations
  • 16. Thread Safe class Demo { private static Collaborator collaborator; public synchronized Collaborator getCollaborator() { if (collaborator == null) { collaborator = new Collaborator(); } return collaborator; } }
  • 17. Optimized Solution class Demo { private static volatile Collaborator collaborator; public Collaborator getCollaborator() { if (collaborator == null) {// double checked locking code synchronized(this) { if (collaborator == null) { collaborator = new Collaborator(); } } } return collaborator; } }
  • 18. Even more Optimized class Demo { private static volatile Collaborator collaborator; public Collaborator getCollaborator() { Collaborator tmp = collaborator; if (tmp == null) { synchronized(this) { if (tmp == null) { tmp = new Collaborator(); collaborator = tmp; } } } return tmp; } }
  • 19. Agenda  Objective  Facts  ThreadSafety  Java Concurrency Problems (Symptoms)  Java Concurrency methods
  • 20. Java Concurrency Problems and Symptoms  Invalid States  Stale values (old values, other threads values)  Null pointer exceptions  Array out of bound exceptions  Symptom  Code works in Debugging while not working in the running mode or production mode  Working with JVM vendor while not working with other  Working with certain usage load and doesn’t work when the usage is increased (JIT Compiler)
  • 21. Agenda  Objective  Facts  ThreadSafety  Java Concurrency Problems (Symptoms)  Java Concurrency methods
  • 22. Java Concurrency methods  Thread Confinement  Stack Confinement  Immutable  Visibility  Atomicity
  • 23. Thread confinement (Not to share)  If data is only accessed from a single thread, no synchronization is needed.  JDBC Connections , confines the connection for a single thread  Implementation using ThreadLocal
  • 24. Thread Confinement public class ConnectionDispenser { private static class ThreadLocalConnection extends ThreadLocal { public Object initialValue() { return DriverManager. getConnection(ConfigurationSingleton.getDbUrl()); } } private static ThreadLocalConnection conn = new ThreadLocalConnection(); public static Connection getConnection() { return (Connection) conn.get(); } }
  • 25. Stack Confinement Not to share  Object can only reached using local variables.  Widely used in our projects public class Income extends HttpServlet { @override protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { IncomeForm income = Util.jsonToObject(input, IncomeForm.class);
  • 26. Immutable  Fieldsare Final , values are set only from the constructors, (this reference does not escaped)  Immutable V effectively Immutable (Fields are not declared final, but there are not setters methods )  Volatile Reference to Immutable Objects
  • 27. Illustrative example @Immutable class OneValueCache { private final BigInteger lastNumber; private final BigInteger[] lastFactors; public OneValueCache(BigInteger i, BigInteger[] factors) { lastNumber = i; lastFactors = Arrays.copyOf(factors, factors.length); } public BigInteger[] getFactors(BigInteger i) { if (lastNumber == null !lastNumber.equals(i)) return null; else return Arrays.copyOf(lastFactors, lastFactors.length); } }
  • 28. Using volatile to publish immutable objects @ThreadSafe public class VolatileCachedFactorizer implements Servlet { private volatile OneValueCache cache = new OneValueCache(null, null); public void service(ServletRequest req, ServletResponse resp) { BigInteger i = extractFromRequest(req); BigInteger[] factors = cache.getFactors(i); //Tip !!! if (factors == null) { factors = factor(i); cache = new OneValueCache(i, factors); } encodeIntoResponse(resp, factors); } }
  • 29. Volatile volatile boolean shutdownRequested; ... public void shutdown() { shutdownRequested = true; } public void doWork() { while (!shutdownRequested) { // do stuff } }
  • 30. Synchronized class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } }
  • 31. Agenda  Objective  Facts  ThreadSafety  Java Concurrency Problems (Symptoms)  Java Concurrency methods
  • 32. References  Java Concurrency in Practice  https://www.student.cs.uwaterloo.ca/~cs 350/W11/notes/threads.pdf  http://antrix.net/posts/2012/java-lazy- initialization/?c=1276