MULTITHREADING IN JAVA
Major release versions               JDK 1.0 (January 21, 1996)                JDK 1.1 (February 19, 1997)               J...
WHATS …. THREAD??!Un thread, o thread di esecuzione, in informatica, è una suddivisionedi un processo in due o più filoni ...
Unimmagine più esplicativa...
Scriviamolo in Java...class ThreadMain {    public static void main(String[] args) {        MyBusinessObject mbs = new MyB...
Function / Methodmethodname( ...args... ) {–   Istruzione1–   Istruzione2–   DescriptiveStatistics de = new DescriptiveSta...
La classe MyBusinessObject è safeness                      ?class MyBusinessObject {    Boolean lock = false;    AtomicBoo...
TCP Socket in Java <1.4: Serverpublic class Server { //Main THREAD    private ExecutorService executors = Executors.newFix...
TCP Socket in Java <1.4: Workerprivate class Worker extends Thread {  private LineNumberReader in = null;  ...  Worker(Soc...
TCP Socket in Java <1.4: run method public void run() {  while (true) {      try {        // blocking read of a request (l...
TCP Socket in Java >= 1.4                            Reactor Pattern...while (TRUE) { //Main THREAD  // blocking call, to ...
TCP Socket in Java >= 1.7NIO2: The asynchronous channel APIs●    AsynchronousSocketChannel●    AsynchronousServerSocketCha...
REFERENCES    Architecture of a Highly Scalable NIO-Based Serverhttp://today.java.net/pub/a/today/2007/02/13/architecture-...
Upcoming SlideShare
Loading in...5
×

Multithreading in Java

405

Published on

Talk tenuto da Flavio Marchi durante il TalkLan del 11 Aprile.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
405
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
14
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Multithreading in Java

  1. 1. MULTITHREADING IN JAVA
  2. 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 NIOJ2SE 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. 3. WHATS …. THREAD??!Un thread, o thread di esecuzione, in informatica, è una suddivisionedi un processo in due o più filoni o sottoprocessi, che vengonoeseguiti concorrentemente da un sistema di elaborazionemonoprocessore (multithreading) o multiprocessore.Fonte: it.wikipedia.org
  4. 4. Unimmagine più esplicativa...
  5. 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. 6. Function / Methodmethodname( ...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. 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)) { // Im safe!! } }}
  8. 8. TCP Socket in Java <1.4: Serverpublic 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. 9. TCP Socket in Java <1.4: Workerprivate 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. 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. 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. 12. TCP Socket in Java >= 1.7NIO2: The asynchronous channel APIs● AsynchronousSocketChannel● AsynchronousServerSocketChannel● AsynchronousFileChannel● AsynchronousDatagramChannelFuture<AsynchronousSocketChannel> acceptFuture = server.accept();ORCompletionHandler<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. 13. REFERENCES Architecture of a Highly Scalable NIO-Based Serverhttp://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/
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×