KEMBAR78
Multithreading in Java | PDF
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/

Multithreading in Java

  • 1.
  • 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??! Unthread, 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
  • 4.
  • 5.
    Scriviamolo in Java... classThreadMain { 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 inJava <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 inJava <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 inJava <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 inJava >= 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 inJava >= 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/