Your SlideShare is downloading. ×
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Multithreading in Java
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Multithreading in Java

334

Published on

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

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
334
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
9
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. 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 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. 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. Unimmagine più esplicativa...
  • 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 / 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. 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. 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. 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. 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.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. 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/

×