SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
MULTITHREADING IN JAVA
Major release versions
               JDK 1.0 (January 21, 1996)

                JDK 1.1 (February 19, 1997)

               J2SE 1.2 (December 8, 1998)

                  J2SE 1.3 (May 8, 2000)

           J2SE 1.4 (February 6, 2002) # api NIO

J2SE 5.0 (September 30, 2004) # package java.util.concurrent

              Java SE 6 (December 11, 2006)

           Java SE 7 (July 28, 2011) # api NIO2

       Java SE 8 (is expected in September, 2013)

Java SE 9 (2015) # automatic parallelization using OpenCL
WHAT'S …. THREAD??!
Un thread, o thread di esecuzione, in informatica, è una suddivisione
di un processo in due o più filoni o sottoprocessi, che vengono
eseguiti concorrentemente da un sistema di elaborazione
monoprocessore (multithreading) o multiprocessore.
Fonte: it.wikipedia.org
Un'immagine più esplicativa...
Scriviamolo in Java...
class ThreadMain {
    public static void main(String[] args) {
        MyBusinessObject mbs = new MyBusinessObject();
        Worker w1 = new Worker(mbs); w1.start();
        Worker w2 = new Worker(mbs); w2.start();
    }

    class Worker extends Thread { run() { … } }
}

class MyBusinessObject {

    Boolean value = false;
    AtomicBoolean atomicvalue = new AtomicBoolean(false);

    Function1() { …. } //funzione uno che accede al campo della classe

    Function2() { …. } //funzione due che accede al campo della classe

}
Function / Method
methodname( ...args... ) {


–   Istruzione1
–   Istruzione2
–   DescriptiveStatistics de = new DescriptiveStatistics(doublearryay);
–   max = de.getMax(); // long computation
–   min = de.getMin();// long computation
–   avg = de.getMean(); // long computation
–   Istruzione7
–   Istruzione8
–   Ecc...


}
La classe MyBusinessObject è safeness
                      ?
class MyBusinessObject {

    Boolean lock = false;
    AtomicBoolean atomicvalue = new AtomicBoolean(false); //java.util.concurrent
    // other references...

    Function1() {
       If(!lock) {
            //do something …. am I really 'safe' ?
       }
    }

    Function2() {
        //Semantic: AtomicBoolean.compareAndSet(boolean expect, boolean update)
        if(atomicValue.compareAndSet(false,true)) {
             // I'm safe!!
        }
    }

}
TCP Socket in Java <1.4: Server
public class Server { //Main THREAD

    private ExecutorService executors = Executors.newFixedThreadPool(10);

    public static void main(String... args) throws ... {
       new Server().launch(Integer.parseInt(args[0]));
     }

    public void launch(int port) throws ... {
       ServerSocket sso = new ServerSocket(port);
       while (true) {
           Socket s = sso.accept(); // bloccante

            Worker w = new Worker(s); // 1.4 style
            w.start();

            executors.execute(new Worker(s)); // ExecutorService in 1.5
        }
    }

}
TCP Socket in Java <1.4: Worker

private class Worker extends Thread {

  private LineNumberReader in = null;
  ...

  Worker(Socket s) throws ... {
     setName(“Pippo Thread ” + new Random().nextInt());
     in = new LineNumberReader(new InputStreamReader(...));
     out = ...
  }

  public void run() {
     //esecuzione del codice da parte del thread
  }

 }
TCP Socket in Java <1.4: run method
 public void run() {
  while (true) {
      try {
        // blocking read of a request (line)
        String request = in.readLine();

         // processing the request
         ...
         String response = ...

         // return the response
         out.write(resonse);
         out.flush();
        } catch (Exception e ) { ….. }
     }
     out.close();
     in.close();
 }
TCP Socket in Java >= 1.4
                            Reactor Pattern
...
while (TRUE) { //Main THREAD
  // blocking call, to wait for new readiness events
  int eventCount = selector.select();

    // get the events
    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
    while (it.hasNext()) {
       SelectionKey key = it.next();
       it.remove();

          if (key.isValid() && key.isReadable()) { // readable event?
            eventHandler.onReadableEvent(key.channel());
          }

          if (key.isValid() && key.isWritable()) { // writable event?
            key.interestOps(SelectionKey.OP_READ); // reset to read only
            eventHandler.onWriteableEvent(key.channel());
          }
          ...
    }
    ...
}
TCP Socket in Java >= 1.7
NIO2: The asynchronous channel APIs
●    AsynchronousSocketChannel
●    AsynchronousServerSocketChannel
●    AsynchronousFileChannel
●    AsynchronousDatagramChannel


Future<AsynchronousSocketChannel> acceptFuture = server.accept();

OR

CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {
   @Override
   public void completed(Integer result, Object attachment) {
     System.out.println(attach+ " completed with " + result + " bytes written");
   }
   @Override
   public void failed(Throwable e, Object attachment) {
     System.err.println(attachment + " failed with:");
      e.printStackTrace();
   }
};
REFERENCES

    Architecture of a Highly Scalable NIO-Based Server

http://today.java.net/pub/a/today/2007/02/13/architecture-of-
                highly-scalable-nio-server.html


 An NIO.2 primer, Part 1: The asynchronous channel APIs

    http://www.ibm.com/developerworks/library/j-nio2-1/

Contenu connexe

Tendances

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
myrajendra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 

Tendances (19)

Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java threading
Java threadingJava threading
Java threading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Thread
ThreadThread
Thread
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 

Similaire à Multithreading in Java

Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 

Similaire à Multithreading in Java (20)

Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Lecture10
Lecture10Lecture10
Lecture10
 
What`s new in Java 7
What`s new in Java 7What`s new in Java 7
What`s new in Java 7
 
Server1
Server1Server1
Server1
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
 
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?
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
 
Thread
ThreadThread
Thread
 
The Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on AndroidThe Mayans Lost Guide to RxJava on Android
The Mayans Lost Guide to RxJava on Android
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 

Plus de Appsterdam Milan

Appsterdam Milan Winter Launch
Appsterdam Milan Winter LaunchAppsterdam Milan Winter Launch
Appsterdam Milan Winter Launch
Appsterdam Milan
 

Plus de Appsterdam Milan (18)

App Store Optimisation
App Store OptimisationApp Store Optimisation
App Store Optimisation
 
iOS Accessibility
iOS AccessibilityiOS Accessibility
iOS Accessibility
 
Lean Startup in Action
Lean Startup in ActionLean Startup in Action
Lean Startup in Action
 
Giocare con il fuoco: Firebase
Giocare con il fuoco: FirebaseGiocare con il fuoco: Firebase
Giocare con il fuoco: Firebase
 
Data visualization e fitness app!
Data visualization e fitness app!Data visualization e fitness app!
Data visualization e fitness app!
 
iBeacon, il faro a bassa energia...
iBeacon, il faro a bassa energia...iBeacon, il faro a bassa energia...
iBeacon, il faro a bassa energia...
 
Facciamo delle slide migliori!
Facciamo delle slide migliori!Facciamo delle slide migliori!
Facciamo delle slide migliori!
 
Fitness for developer
Fitness for developerFitness for developer
Fitness for developer
 
Follow the UX path
Follow the UX pathFollow the UX path
Follow the UX path
 
Dalla black box alla scatola nera
Dalla black box alla scatola neraDalla black box alla scatola nera
Dalla black box alla scatola nera
 
Java Search Engine Framework
Java Search Engine FrameworkJava Search Engine Framework
Java Search Engine Framework
 
iOS design patterns: blocks
iOS design patterns: blocksiOS design patterns: blocks
iOS design patterns: blocks
 
Data binding libera tutti!
Data binding libera tutti!Data binding libera tutti!
Data binding libera tutti!
 
Speech for Windows Phone 8
Speech for Windows Phone 8Speech for Windows Phone 8
Speech for Windows Phone 8
 
Web frameworks
Web frameworksWeb frameworks
Web frameworks
 
Interfacciamento di iPhone ed iPad
Interfacciamento di iPhone ed iPadInterfacciamento di iPhone ed iPad
Interfacciamento di iPhone ed iPad
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Appsterdam Milan Winter Launch
Appsterdam Milan Winter LaunchAppsterdam Milan Winter Launch
Appsterdam Milan Winter Launch
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Multithreading in Java

  • 2. Major release versions JDK 1.0 (January 21, 1996) JDK 1.1 (February 19, 1997) J2SE 1.2 (December 8, 1998) J2SE 1.3 (May 8, 2000) J2SE 1.4 (February 6, 2002) # api NIO J2SE 5.0 (September 30, 2004) # package java.util.concurrent Java SE 6 (December 11, 2006) Java SE 7 (July 28, 2011) # api NIO2 Java SE 8 (is expected in September, 2013) Java SE 9 (2015) # automatic parallelization using OpenCL
  • 3. WHAT'S …. THREAD??! Un thread, o thread di esecuzione, in informatica, è una suddivisione di un processo in due o più filoni o sottoprocessi, che vengono eseguiti concorrentemente da un sistema di elaborazione monoprocessore (multithreading) o multiprocessore. Fonte: it.wikipedia.org
  • 5. Scriviamolo in Java... class ThreadMain { public static void main(String[] args) { MyBusinessObject mbs = new MyBusinessObject(); Worker w1 = new Worker(mbs); w1.start(); Worker w2 = new Worker(mbs); w2.start(); } class Worker extends Thread { run() { … } } } class MyBusinessObject { Boolean value = false; AtomicBoolean atomicvalue = new AtomicBoolean(false); Function1() { …. } //funzione uno che accede al campo della classe Function2() { …. } //funzione due che accede al campo della classe }
  • 6. Function / Method methodname( ...args... ) { – Istruzione1 – Istruzione2 – DescriptiveStatistics de = new DescriptiveStatistics(doublearryay); – max = de.getMax(); // long computation – min = de.getMin();// long computation – avg = de.getMean(); // long computation – Istruzione7 – Istruzione8 – Ecc... }
  • 7. La classe MyBusinessObject è safeness ? class MyBusinessObject { Boolean lock = false; AtomicBoolean atomicvalue = new AtomicBoolean(false); //java.util.concurrent // other references... Function1() { If(!lock) { //do something …. am I really 'safe' ? } } Function2() { //Semantic: AtomicBoolean.compareAndSet(boolean expect, boolean update) if(atomicValue.compareAndSet(false,true)) { // I'm safe!! } } }
  • 8. TCP Socket in Java <1.4: Server public class Server { //Main THREAD private ExecutorService executors = Executors.newFixedThreadPool(10); public static void main(String... args) throws ... { new Server().launch(Integer.parseInt(args[0])); } public void launch(int port) throws ... { ServerSocket sso = new ServerSocket(port); while (true) { Socket s = sso.accept(); // bloccante Worker w = new Worker(s); // 1.4 style w.start(); executors.execute(new Worker(s)); // ExecutorService in 1.5 } } }
  • 9. TCP Socket in Java <1.4: Worker private class Worker extends Thread { private LineNumberReader in = null; ... Worker(Socket s) throws ... { setName(“Pippo Thread ” + new Random().nextInt()); in = new LineNumberReader(new InputStreamReader(...)); out = ... } public void run() { //esecuzione del codice da parte del thread } }
  • 10. TCP Socket in Java <1.4: run method public void run() { while (true) { try { // blocking read of a request (line) String request = in.readLine(); // processing the request ... String response = ... // return the response out.write(resonse); out.flush(); } catch (Exception e ) { ….. } } out.close(); in.close(); }
  • 11. TCP Socket in Java >= 1.4 Reactor Pattern ... while (TRUE) { //Main THREAD // blocking call, to wait for new readiness events int eventCount = selector.select(); // get the events Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); if (key.isValid() && key.isReadable()) { // readable event? eventHandler.onReadableEvent(key.channel()); } if (key.isValid() && key.isWritable()) { // writable event? key.interestOps(SelectionKey.OP_READ); // reset to read only eventHandler.onWriteableEvent(key.channel()); } ... } ... }
  • 12. TCP Socket in Java >= 1.7 NIO2: The asynchronous channel APIs ● AsynchronousSocketChannel ● AsynchronousServerSocketChannel ● AsynchronousFileChannel ● AsynchronousDatagramChannel Future<AsynchronousSocketChannel> acceptFuture = server.accept(); OR CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() { @Override public void completed(Integer result, Object attachment) { System.out.println(attach+ " completed with " + result + " bytes written"); } @Override public void failed(Throwable e, Object attachment) { System.err.println(attachment + " failed with:"); e.printStackTrace(); } };
  • 13. REFERENCES Architecture of a Highly Scalable NIO-Based Server http://today.java.net/pub/a/today/2007/02/13/architecture-of- highly-scalable-nio-server.html An NIO.2 primer, Part 1: The asynchronous channel APIs http://www.ibm.com/developerworks/library/j-nio2-1/