SlideShare a Scribd company logo
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/

More Related Content

What's hot

Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
M. Raihan
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
aalipalh
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
jehan1987
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
Gaurav Aggarwal
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Lovely Professional University
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Thread
ThreadThread
Thread
Juhi Kumari
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 

What's hot (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
 

Similar to Multithreading in Java

Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
What`s new in Java 7
What`s new in Java 7What`s new in Java 7
What`s new in Java 7
Georgian Micsa
 
Server1
Server1Server1
Server1
FahriIrawan3
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
feng lee
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
bloodredsun
 
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
 
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
Rafael Winterhalter
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
wahyuseptiansyah
 
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
Fernando Cejas
 
Async Best Practices
Async Best PracticesAsync Best Practices
Async Best Practices
Lluis Franco
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
Roger Xia
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
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 TestsTomek Kaczanowski
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
Danairat Thanabodithammachari
 

Similar to 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
 

More from Appsterdam Milan

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

More from 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
 

Recently uploaded

FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
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
FIDO Alliance
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
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
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 

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/