SlideShare a Scribd company logo
1 of 39
Download to read offline
http://gee.cs.oswego.edu




                                Scalable IO in Java



                                          Doug Lea
                           State University of New York at Oswego
                                   dl@cs.oswego.edu
                              http://gee.cs.oswego.edu
Outline
                               Scalable network services
                           quot;
http://gee.cs.oswego.edu




                               Event-driven processing
                           quot;




                               Reactor pattern
                           quot;


                                 Basic version
                                 Multithreaded versions
                                 Other variants

                               Walkthrough of java.nio nonblocking IO APIs
                           quot;
Network Services
                               Web services, Distributed Objects, etc
                           quot;
http://gee.cs.oswego.edu




                               Most have same basic structure:
                           quot;


                                 Read request
                                 Decode request
                                 Process service
                                 Encode reply
                                 Send reply
                               But differ in nature and cost of each step
                           quot;


                                 XML parsing, File transfer, Web page
                                 generation, computational services, ...
Classic Service Designs
http://gee.cs.oswego.edu




                                                           decode compute encode   send
                                                    read
                            client
                                                                 handler
                                                           decode compute encode   send
                                                    read
                            client      Server                   handler

                                                           decode compute encode   send
                                                    read
                            client
                                                                 handler



                           Each handler may be started in its own thread
Classic ServerSocket Loop
                           class Server implements Runnable {
                             public void run() {
                               try {
http://gee.cs.oswego.edu



                                 ServerSocket ss = new ServerSocket(PORT);
                                 while (!Thread.interrupted())
                                   new Thread(new Handler(ss.accept())).start();
                                 // or, single-threaded, or a thread pool
                               } catch (IOException ex) { /* ... */ }
                             }

                             static class Handler implements Runnable {
                               final Socket socket;
                               Handler(Socket s) { socket = s; }
                               public void run() {
                                 try {
                                   byte[] input = new byte[MAX_INPUT];
                                   socket.getInputStream().read(input);
                                   byte[] output = process(input);
                                   socket.getOutputStream().write(output);
                                 } catch (IOException ex) { /* ... */ }
                               }
                               private byte[] process(byte[] cmd) { /* ... */ }
                             }
                           }
                           Note: most exception handling elided from code examples
Scalability Goals
                               Graceful degradation under increasing load
                           quot;
http://gee.cs.oswego.edu




                               (more clients)
                               Continuous improvement with increasing
                           quot;

                               resources (CPU, memory, disk, bandwidth)
                               Also meet availability and performance goals
                           quot;


                                 Short latencies
                                 Meeting peak demand
                                 Tunable quality of service

                               Divide-and-conquer is usually the best
                           quot;

                               approach for achieving any scalability goal
Divide and Conquer
                               Divide processing into small tasks
                           quot;
http://gee.cs.oswego.edu




                                 Each task performs an action without blocking
                               Execute each task when it is enabled
                           quot;


                                 Here, an IO event usually serves as trigger
                                              decode compute encode   send
                                       read
                                                    handler
                               Basic mechanisms supported in java.nio
                           quot;


                                 Non-blocking reads and writes
                                 Dispatch tasks associated with sensed IO events
                               Endless variation possible
                           quot;


                                 A family of event-driven designs
Event-driven Designs
                               Usually more efficient than alternatives
                           quot;
http://gee.cs.oswego.edu



                                 Fewer resources
                                      Don't usually need a thread per client
                                  quot;



                                 Less overhead
                                      Less context switching, often less locking
                                  quot;



                                 But dispatching can be slower
                                      Must manually bind actions to events
                                  quot;



                               Usually harder to program
                           quot;


                                 Must break up into simple non-blocking actions
                                      Similar to GUI event-driven actions
                                  quot;


                                      Cannot eliminate all blocking: GC, page faults, etc
                                  quot;



                                 Must keep track of logical state of service
Background: Events in AWT
                                    AWT Event Queue
http://gee.cs.oswego.edu




                                       Event
                                       ...
                                                              Button
                                       Event


                                               AWT thread
                           click!
                                                        ActionListener
                                               public void actionPerformed(...) {
                                                 doSomething();
                                               }




                           Event-driven IO uses similar ideas but in different designs
Reactor Pattern
                               Reactor responds to IO events by dispatching
                           quot;

                               the appropriate handler
http://gee.cs.oswego.edu




                                 Similar to AWT thread
                               Handlers perform non-blocking actions
                           quot;


                                 Similar to AWT ActionListeners
                               Manage by binding handlers to events
                           quot;


                                 Similar to AWT addActionListener
                               See Schmidt et al, Pattern-Oriented Software
                           quot;

                               Architecture, Volume 2 (POSA2)
                                 Also Richard Stevens's networking books, Matt
                                 Welsh's SEDA framework, etc
Basic Reactor Design
http://gee.cs.oswego.edu




                                                            Reactor
                           client
                                                             dispatch
                           client
                                                             decode compute encode   send
                                                     read

                                                             decode compute encode   send
                                                     read
                           client
                                                             decode compute encode   send
                                      acceptor       read




                           Single threaded version
java.nio Support
                               Channels
                           quot;
http://gee.cs.oswego.edu




                                 Connections to files, sockets etc that support
                                 non-blocking reads
                               Buffers
                           quot;


                                 Array-like objects that can be directly read or
                                 written by Channels
                               Selectors
                           quot;


                                 Tell which of a set of Channels have IO events
                               SelectionKeys
                           quot;


                                 Maintain IO event status and bindings
Reactor 1: Setup
                           class Reactor implements Runnable {
                             final Selector selector;
                             final ServerSocketChannel serverSocket;
http://gee.cs.oswego.edu




                             Reactor(int port) throws IOException {
                               selector = Selector.open();
                               serverSocket = ServerSocketChannel.open();
                               serverSocket.socket().bind(
                                              new InetSocketAddress(port));
                               serverSocket.configureBlocking(false);
                               SelectionKey sk =
                                 serverSocket.register(selector,

                           SelectionKey.OP_ACCEPT);
                               sk.attach(new Acceptor());
                             }
                             /*
                              Alternatively, use explicit SPI provider:
                                SelectorProvider p = SelectorProvider.provider();
                                selector = p.openSelector();
                                serverSocket = p.openServerSocketChannel();
                             */
Reactor 2: Dispatch Loop
                           // class Reactor continued
                             public void run() { // normally in a new
                           Thread
http://gee.cs.oswego.edu



                               try {
                                  while (!Thread.interrupted()) {
                                    selector.select();
                                    Set selected = selector.selectedKeys();
                                    Iterator it = selected.iterator();
                                    while (it.hasNext())
                                      dispatch((SelectionKey)(it.next());
                                    selected.clear();
                                  }
                               } catch (IOException ex) { /* ... */ }
                             }

                             void dispatch(SelectionKey k) {
                               Runnable r = (Runnable)(k.attachment());
                               if (r != null)
                                 r.run();
                             }
Reactor 3: Acceptor
                           // class Reactor continued
                             class Acceptor implements Runnable { // inner
http://gee.cs.oswego.edu



                               public void run() {
                                 try {
                                   SocketChannel c = serverSocket.accept();
                                   if (c != null)
                                     new Handler(selector, c);
                                 }
                                 catch(IOException ex) { /* ... */ }
                               }
                             }
                           }
                                                       Reactor
                           client
                                                       dispatch
                            client                      decode compute encode   send
                                                read
                                                        decode compute encode   send
                                                read
                            client
                                                        decode compute encode   send
                                     acceptor   read
Reactor 4: Handler setup
                           final class Handler implements Runnable {
                             final SocketChannel socket;
                             final SelectionKey sk;
http://gee.cs.oswego.edu




                             ByteBuffer input = ByteBuffer.allocate(MAXIN);
                             ByteBuffer output = ByteBuffer.allocate(MAXOUT);
                             static final int READING = 0, SENDING = 1;
                             int state = READING;

                             Handler(Selector sel, SocketChannel c)
                               throws IOException {
                                socket = c; c.configureBlocking(false);
                                // Optionally try first read now
                                sk = socket.register(sel, 0);
                                sk.attach(this);
                                sk.interestOps(SelectionKey.OP_READ);
                                sel.wakeup();
                             }

                             boolean inputIsComplete() { /* ... */ }
                             boolean outputIsComplete() { /* ... */ }
                             void process()             { /* ... */ }
Reactor 5: Request handling
                           // class Handler continued
                               public void run() {
                                try {
http://gee.cs.oswego.edu




                                  if      (state == READING) read();
                                  else if (state == SENDING) send();
                                } catch (IOException ex) { /* ... */ }
                             }
                             void read() throws IOException {
                                socket.read(input);
                                if (inputIsComplete()) {
                                   process();
                                   state = SENDING;
                                   // Normally also do first write now
                                   sk.interestOps(SelectionKey.OP_WRITE);
                                }
                             }
                             void send() throws IOException {
                                socket.write(output);
                                if (outputIsComplete()) sk.cancel();
                             }
                           }
Per-State Handlers
                               A simple use of GoF State-Object pattern
                           quot;
http://gee.cs.oswego.edu



                                 Rebind appropriate handler as attachment
                                 class Handler    { // ...
                                     public void run() { // initial state is reader
                                       socket.read(input);
                                       if (inputIsComplete()) {
                                         process();
                                         sk.attach(new Sender());
                                         sk.interest(SelectionKey.OP_WRITE);
                                         sk.selector().wakeup();
                                       }
                                     }
                                     class Sender implements Runnable {
                                       public void run(){ // ...
                                         socket.write(output);
                                         if (outputIsComplete()) sk.cancel();
                                       }
                                     }
                                 }
Multithreaded Designs
                               Strategically add threads for scalability
                           quot;


                                 Mainly applicable to multiprocessors
http://gee.cs.oswego.edu




                               Worker Threads
                           quot;


                                 Reactors should quickly trigger handlers
                                      Handler processing slows down Reactor
                                  quot;



                                 Offload non-IO processing to other threads

                               Multiple Reactor Threads
                           quot;


                                 Reactor threads can saturate doing IO
                                 Distribute load to other reactors
                                      Load-balance to match CPU and IO rates
                                  quot;
Worker Threads
                               Offload non-IO processing to speed up
                           quot;

                               Reactor thread
http://gee.cs.oswego.edu




                                 Similar to POSA2 Proactor designs
                               Simpler than reworking compute-bound
                           quot;

                               processing into event-driven form
                                 Should still be pure nonblocking computation
                                      Enough processing to outweigh overhead
                                  quot;



                               But harder to overlap processing with IO
                           quot;


                                 Best when can first read all input into a buffer
                               Use thread pool so can tune and control
                           quot;


                                 Normally need many fewer threads than clients
Worker Thread Pools
                           client                           Reactor
http://gee.cs.oswego.edu




                           client                                             send
                                                     read

                                                                              send
                                                     read
                                        acceptor
                           client
                                                                              send
                                                     read



                                                     decode compute encode
                                                                             worker
                                          Thread
                                                                             threads
                                          Pool       decode compute encode


                             decode compute encode

                                    queued tasks
Handler with Thread Pool
                           class Handler implements Runnable {
                             // uses util.concurrent thread pool
                             static PooledExecutor pool = new PooledExecutor(...);
http://gee.cs.oswego.edu



                             static final int PROCESSING = 3;
                             // ...

                               synchronized void read() { // ...
                                 socket.read(input);
                                 if (inputIsComplete()) {
                                   state = PROCESSING;
                                   pool.execute(new Processer());
                                 }
                               }

                               synchronized void processAndHandOff() {
                                 process();
                                 state = SENDING; // or rebind attachment
                                 sk.interest(SelectionKey.OP_WRITE);
                               }

                               class Processer implements Runnable {
                                 public void run() { processAndHandOff(); }
                               }
                           }
Coordinating Tasks
                               Handoffs
                           quot;


                                 Each task enables, triggers, or calls next one
http://gee.cs.oswego.edu




                                 Usually fastest but can be brittle
                               Callbacks to per-handler dispatcher
                           quot;


                                 Sets state, attachment, etc
                                 A variant of GoF Mediator pattern
                               Queues
                           quot;


                                 For example, passing buffers across stages
                               Futures
                           quot;


                                 When each task produces a result
                                 Coordination layered on top of join or wait/notify
Using PooledExecutor
                               A tunable worker thread pool
                           quot;


                               Main method execute(Runnable r)
http://gee.cs.oswego.edu



                           quot;


                               Controls for:
                           quot;


                                 The kind of task queue (any Channel)
                                 Maximum number of threads
                                 Minimum number of threads
                                 quot;Warmquot; versus on-demand threads
                                 Keep-alive interval until idle threads die
                                      to be later replaced by new ones if necessary
                                  quot;



                                 Saturation policy
                                      block, drop, producer-runs, etc
                                  quot;
Multiple Reactor Threads
                               Using Reactor Pools
                           quot;
http://gee.cs.oswego.edu



                                 Use to match CPU and IO rates
                                 Static or dynamic construction
                                      Each with own Selector, Thread, dispatch loop
                                  quot;



                                 Main acceptor distributes to other reactors
                                 Selector[] selectors; // also create threads
                                 int next = 0;
                                 class Acceptor { // ...
                                   public synchronized void run() { ...
                                     Socket connection = serverSocket.accept();
                                     if (connection != null)
                                       new Handler(selectors[next], connection);
                                     if (++next == selectors.length) next = 0;
                                   }
                                 }
Using Multiple Reactors
                           client         mainReactor         subReactor
http://gee.cs.oswego.edu




                           client                                             send
                                                     read

                                                                              send
                                                     read
                                        acceptor
                           client
                                                                              send
                                                     read



                                                     decode compute encode
                                                                             worker
                                          Thread
                                                                             threads
                                          Pool       decode compute encode


                             decode compute encode

                                    queued tasks
Using other java.nio features
                               Multiple Selectors per Reactor
                           quot;


                                 To bind different handlers to different IO events
http://gee.cs.oswego.edu




                                 May need careful synchronization to coordinate
                               File transfer
                           quot;


                                 Automated file-to-net or net-to-file copying
                               Memory-mapped files
                           quot;


                                 Access files via buffers
                               Direct buffers
                           quot;


                                 Can sometimes achieve zero-copy transfer
                                 But have setup and finalization overhead
                                 Best for applications with long-lived connections
Connection-Based Extensions
                               Instead of a single service request,
                           quot;
http://gee.cs.oswego.edu



                                 Client connects
                                 Client sends a series of messages/requests
                                 Client disconnects
                               Examples
                           quot;


                                 Databases and Transaction monitors
                                 Multi-participant games, chat, etc
                               Can extend basic network service patterns
                           quot;


                                 Handle many relatively long-lived clients
                                 Track client and session state (including drops)
                                 Distribute services across multiple hosts
API Walkthrough
                               Buffer
                           quot;
http://gee.cs.oswego.edu



                               ByteBuffer
                           quot;


                                 (CharBuffer, LongBuffer, etc not shown.)
                               Channel
                           quot;


                               SelectableChannel
                           quot;


                               SocketChannel
                           quot;


                               ServerSocketChannel
                           quot;


                               FileChannel
                           quot;


                               Selector
                           quot;


                               SelectionKey
                           quot;
Buffer
                           abstract class Buffer {
                             int     capacity();
                             int     position();
http://gee.cs.oswego.edu



                             Buffer position(int newPosition);
                             int     limit();
                             Buffer limit(int newLimit);
                             Buffer mark();
                             Buffer reset();
                             Buffer clear();
                             Buffer flip();
                             Buffer rewind();
                             int     remaining();
                             boolean hasRemaining();
                             boolean isReadOnly();
                           }


                                              abc


                                           position limit        capacity
                             mark
ByteBuffer (1)
                           abstract   class ByteBuffer extends Buffer {
                             static   ByteBuffer allocateDirect(int capacity);
                             static   ByteBuffer allocate(int capacity);
http://gee.cs.oswego.edu



                             static   ByteBuffer wrap(byte[] src, int offset, int len);
                             static   ByteBuffer wrap(byte[] src);

                             boolean        isDirect();
                             ByteOrder      order();
                             ByteBuffer     order(ByteOrder bo);
                             ByteBuffer     slice();
                             ByteBuffer     duplicate();
                             ByteBuffer     compact();
                             ByteBuffer     asReadOnlyBuffer();
                             byte           get();
                             byte           get(int index);
                             ByteBuffer     get(byte[] dst, int offset, int length);
                             ByteBuffer     get(byte[] dst);
                             ByteBuffer     put(byte b);
                             ByteBuffer     put(int index, byte b);
                             ByteBuffer     put(byte[] src, int offset, int length);
                             ByteBuffer     put(ByteBuffer src);
                             ByteBuffer     put(byte[] src);
                             char           getChar();
                             char           getChar(int index);
                             ByteBuffer     putChar(char value);
                             ByteBuffer     putChar(int index, char value);
                             CharBuffer     asCharBuffer();
ByteBuffer (2)
                               short          getShort();
                               short          getShort(int index);
                               ByteBuffer     putShort(short value);
http://gee.cs.oswego.edu



                               ByteBuffer     putShort(int index, short value);
                               ShortBuffer    asShortBuffer();
                               int            getInt();
                               int            getInt(int index);
                               ByteBuffer     putInt(int value);
                               ByteBuffer     putInt(int index, int value);
                               IntBuffer      asIntBuffer();
                               long           getLong();
                               long           getLong(int index);
                               ByteBuffer     putLong(long value);
                               ByteBuffer     putLong(int index, long value);
                               LongBuffer     asLongBuffer();
                               float          getFloat();
                               float          getFloat(int index);
                               ByteBuffer     putFloat(float value);
                               ByteBuffer     putFloat(int index, float value);
                               FloatBuffer    asFloatBuffer();
                               double         getDouble();
                               double         getDouble(int index);
                               ByteBuffer     putDouble(double value);
                               ByteBuffer     putDouble(int index, double value);
                               DoubleBuffer   asDoubleBuffer();
                           }
Channel
                           interface Channel {
                             boolean isOpen();
                             void    close() throws IOException;
http://gee.cs.oswego.edu



                           }

                           interface ReadableByteChannel extends Channel {
                             int     read(ByteBuffer dst) throws IOException;
                           }

                           interface WritableByteChannel extends Channel {
                             int     write(ByteBuffer src) throws IOException;
                           }

                           interface ScatteringByteChannel extends ReadableByteChannel {
                             int     read(ByteBuffer[] dsts, int offset, int length)
                                       throws IOException;
                             int     read(ByteBuffer[] dsts) throws IOException;
                           }

                           interface GatheringByteChannel extends WritableByteChannel {
                             int     write(ByteBuffer[] srcs, int offset, int length)
                                       throws IOException;
                             int     write(ByteBuffer[] srcs) throws IOException;
                           }
SelectableChannel
                           abstract class SelectableChannel implements Channel {
                             int          validOps();
http://gee.cs.oswego.edu



                             boolean      isRegistered();

                               SelectionKey keyFor(Selector sel);
                               SelectionKey register(Selector sel, int ops)
                                               throws ClosedChannelException;

                               void         configureBlocking(boolean block)
                                               throws IOException;
                               boolean      isBlocking();
                               Object       blockingLock();
                           }
SocketChannel
                           abstract class SocketChannel implements ByteChannel ... {
                             static SocketChannel open() throws IOException;
http://gee.cs.oswego.edu



                               Socket    socket();
                               int       validOps();
                               boolean   isConnected();
                               boolean   isConnectionPending();
                               boolean   isInputOpen();
                               boolean   isOutputOpen();

                               boolean   connect(SocketAddress remote) throws IOException;
                               boolean   finishConnect() throws IOException;
                               void      shutdownInput() throws IOException;
                               void      shutdownOutput() throws IOException;

                               int       read(ByteBuffer dst) throws IOException;
                               int       read(ByteBuffer[] dsts, int offset, int length)
                                             throws IOException;
                               int       read(ByteBuffer[] dsts) throws IOException;

                               int       write(ByteBuffer src) throws IOException;
                               int       write(ByteBuffer[] srcs, int offset, int length)
                                             throws IOException;
                               int       write(ByteBuffer[] srcs) throws IOException;
                           }
ServerSocketChannel
                           abstract class ServerSocketChannel extends ... {
                             static ServerSocketChannel open() throws IOException;
http://gee.cs.oswego.edu




                               int           validOps();
                               ServerSocket socket();
                               SocketChannel accept() throws IOException;
                           }
FileChannel
                           abstract class FileChannel implements ... {
                             int read(ByteBuffer dst);
                             int read(ByteBuffer dst, long position);
http://gee.cs.oswego.edu



                             int read(ByteBuffer[] dsts, int offset, int length);
                             int read(ByteBuffer[] dsts);
                             int write(ByteBuffer src);
                             int write(ByteBuffer src, long position);
                             int write(ByteBuffer[] srcs, int offset, int length);
                             int write(ByteBuffer[] srcs);
                             long position();
                             void position(long newPosition);
                             long size();
                             void truncate(long size);
                             void force(boolean flushMetaDataToo);
                             int transferTo(long position, int count,
                                              WritableByteChannel dst);
                             int transferFrom(ReadableByteChannel src,
                                                long position, int count);
                             FileLock lock(long position, long size, boolean shared);
                             FileLock lock();
                             FileLock tryLock(long pos, long size, boolean shared);
                             FileLock tryLock();
                             static final int MAP_RO, MAP_RW, MAP_COW;
                             MappedByteBuffer map(int mode, long position, int size);
                           }
                           NOTE: ALL methods throw IOException
Selector
                           abstract class Selector {
                             static Selector open() throws IOException;
                             Set keys();
http://gee.cs.oswego.edu



                             Set selectedKeys();
                             int selectNow() throws IOException;
                             int select(long timeout) throws IOException;
                             int select() throws IOException;
                             void wakeup();
                             void close() throws IOException;
                           }
SelectionKey
                           abstract class SelectionKey {
                             static final int OP_READ,     OP_WRITE,
                                               OP_CONNECT, OP_ACCEPT;
http://gee.cs.oswego.edu



                             SelectableChannel channel();
                             Selector          selector();
                             boolean           isValid();
                             void              cancel();
                             int               interestOps();
                             void              interestOps(int ops);
                             int               readyOps();
                             boolean           isReadable();
                             boolean           isWritable();
                             boolean           isConnectable();
                             boolean           isAcceptable();
                             Object            attach(Object ob);
                             Object            attachment();
                           }

More Related Content

What's hot

Zookeeper In Simple Words
Zookeeper In Simple WordsZookeeper In Simple Words
Zookeeper In Simple WordsFuqiang Wang
 
OrientDB the graph database
OrientDB the graph databaseOrientDB the graph database
OrientDB the graph databaseArtem Orobets
 
Practicing Continuous Deployment
Practicing Continuous DeploymentPracticing Continuous Deployment
Practicing Continuous Deploymentzeeg
 
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorGr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorStanislav Tiurikov
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Greg Szczotka
 
A Groovy Kind of Java (San Francisco Java User Group)
A Groovy Kind of Java (San Francisco Java User Group)A Groovy Kind of Java (San Francisco Java User Group)
A Groovy Kind of Java (San Francisco Java User Group)Nati Shalom
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questionstechievarsity
 
Metarhia: Node.js Macht Frei
Metarhia: Node.js Macht FreiMetarhia: Node.js Macht Frei
Metarhia: Node.js Macht FreiTimur Shemsedinov
 
Zookeeper big sonata
Zookeeper  big sonataZookeeper  big sonata
Zookeeper big sonataAnh Le
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Haim Yadid
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojosdeconf
 
Memcached Code Camp 2009
Memcached Code Camp 2009Memcached Code Camp 2009
Memcached Code Camp 2009NorthScale
 
Moxi - Memcached Proxy
Moxi - Memcached ProxyMoxi - Memcached Proxy
Moxi - Memcached ProxyNorthScale
 
ATG Secure Repository
ATG Secure RepositoryATG Secure Repository
ATG Secure RepositorySanju Thomas
 
What istheservicestack
What istheservicestackWhat istheservicestack
What istheservicestackDemis Bellot
 

What's hot (20)

Zookeeper In Simple Words
Zookeeper In Simple WordsZookeeper In Simple Words
Zookeeper In Simple Words
 
Brubeck: Overview
Brubeck: OverviewBrubeck: Overview
Brubeck: Overview
 
OrientDB the graph database
OrientDB the graph databaseOrientDB the graph database
OrientDB the graph database
 
Memcached Study
Memcached StudyMemcached Study
Memcached Study
 
Practicing Continuous Deployment
Practicing Continuous DeploymentPracticing Continuous Deployment
Practicing Continuous Deployment
 
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorGr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014
 
A Groovy Kind of Java (San Francisco Java User Group)
A Groovy Kind of Java (San Francisco Java User Group)A Groovy Kind of Java (San Francisco Java User Group)
A Groovy Kind of Java (San Francisco Java User Group)
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questions
 
Html5 security
Html5 securityHtml5 security
Html5 security
 
Metarhia: Node.js Macht Frei
Metarhia: Node.js Macht FreiMetarhia: Node.js Macht Frei
Metarhia: Node.js Macht Frei
 
Zookeeper big sonata
Zookeeper  big sonataZookeeper  big sonata
Zookeeper big sonata
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojo
 
Memcached Code Camp 2009
Memcached Code Camp 2009Memcached Code Camp 2009
Memcached Code Camp 2009
 
Nodejs in Production
Nodejs in ProductionNodejs in Production
Nodejs in Production
 
Moxi - Memcached Proxy
Moxi - Memcached ProxyMoxi - Memcached Proxy
Moxi - Memcached Proxy
 
ATG Secure Repository
ATG Secure RepositoryATG Secure Repository
ATG Secure Repository
 
Intro to J Ruby
Intro to J RubyIntro to J Ruby
Intro to J Ruby
 
What istheservicestack
What istheservicestackWhat istheservicestack
What istheservicestack
 

Similar to Nio

Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tourcacois
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS drupalcampest
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Node Security: The Good, Bad & Ugly
Node Security: The Good, Bad & UglyNode Security: The Good, Bad & Ugly
Node Security: The Good, Bad & UglyBishan Singh
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialTom Croucher
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebBhagaban Behera
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsGary Yeh
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)Tech in Asia ID
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 

Similar to Nio (20)

Scalable io in java
Scalable io in javaScalable io in java
Scalable io in java
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
Node Security: The Good, Bad & Ugly
Node Security: The Good, Bad & UglyNode Security: The Good, Bad & Ugly
Node Security: The Good, Bad & Ugly
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Node.js - As a networking tool
Node.js - As a networking toolNode.js - As a networking tool
Node.js - As a networking tool
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
Node js internal
Node js internalNode js internal
Node js internal
 
GeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime WebGeekCampSG - Nodejs , Websockets and Realtime Web
GeekCampSG - Nodejs , Websockets and Realtime Web
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Node.js on Azure
Node.js on AzureNode.js on Azure
Node.js on Azure
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Node
NodeNode
Node
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 

More from nextlib

Hadoop Map Reduce Arch
Hadoop Map Reduce ArchHadoop Map Reduce Arch
Hadoop Map Reduce Archnextlib
 
D Rb Silicon Valley Ruby Conference
D Rb   Silicon Valley Ruby ConferenceD Rb   Silicon Valley Ruby Conference
D Rb Silicon Valley Ruby Conferencenextlib
 
Multi-core architectures
Multi-core architecturesMulti-core architectures
Multi-core architecturesnextlib
 
Aldous Huxley Brave New World
Aldous Huxley Brave New WorldAldous Huxley Brave New World
Aldous Huxley Brave New Worldnextlib
 
Social Graph
Social GraphSocial Graph
Social Graphnextlib
 
Ajax Prediction
Ajax PredictionAjax Prediction
Ajax Predictionnextlib
 
Closures for Java
Closures for JavaClosures for Java
Closures for Javanextlib
 
A Content-Driven Reputation System for the Wikipedia
A Content-Driven Reputation System for the WikipediaA Content-Driven Reputation System for the Wikipedia
A Content-Driven Reputation System for the Wikipedianextlib
 
SVD review
SVD reviewSVD review
SVD reviewnextlib
 
Mongrel Handlers
Mongrel HandlersMongrel Handlers
Mongrel Handlersnextlib
 
Blue Ocean Strategy
Blue Ocean StrategyBlue Ocean Strategy
Blue Ocean Strategynextlib
 
日本7-ELEVEN消費心理學
日本7-ELEVEN消費心理學日本7-ELEVEN消費心理學
日本7-ELEVEN消費心理學nextlib
 
Comparing State-of-the-Art Collaborative Filtering Systems
Comparing State-of-the-Art Collaborative Filtering SystemsComparing State-of-the-Art Collaborative Filtering Systems
Comparing State-of-the-Art Collaborative Filtering Systemsnextlib
 
Item Based Collaborative Filtering Recommendation Algorithms
Item Based Collaborative Filtering Recommendation AlgorithmsItem Based Collaborative Filtering Recommendation Algorithms
Item Based Collaborative Filtering Recommendation Algorithmsnextlib
 
Agile Adoption2007
Agile Adoption2007Agile Adoption2007
Agile Adoption2007nextlib
 
Modern Compiler Design
Modern Compiler DesignModern Compiler Design
Modern Compiler Designnextlib
 
透过众神的眼睛--鸟瞰非洲
透过众神的眼睛--鸟瞰非洲透过众神的眼睛--鸟瞰非洲
透过众神的眼睛--鸟瞰非洲nextlib
 
Improving Quality of Search Results Clustering with Approximate Matrix Factor...
Improving Quality of Search Results Clustering with Approximate Matrix Factor...Improving Quality of Search Results Clustering with Approximate Matrix Factor...
Improving Quality of Search Results Clustering with Approximate Matrix Factor...nextlib
 
Support Vector Machines
Support Vector MachinesSupport Vector Machines
Support Vector Machinesnextlib
 
Bigtable
BigtableBigtable
Bigtablenextlib
 

More from nextlib (20)

Hadoop Map Reduce Arch
Hadoop Map Reduce ArchHadoop Map Reduce Arch
Hadoop Map Reduce Arch
 
D Rb Silicon Valley Ruby Conference
D Rb   Silicon Valley Ruby ConferenceD Rb   Silicon Valley Ruby Conference
D Rb Silicon Valley Ruby Conference
 
Multi-core architectures
Multi-core architecturesMulti-core architectures
Multi-core architectures
 
Aldous Huxley Brave New World
Aldous Huxley Brave New WorldAldous Huxley Brave New World
Aldous Huxley Brave New World
 
Social Graph
Social GraphSocial Graph
Social Graph
 
Ajax Prediction
Ajax PredictionAjax Prediction
Ajax Prediction
 
Closures for Java
Closures for JavaClosures for Java
Closures for Java
 
A Content-Driven Reputation System for the Wikipedia
A Content-Driven Reputation System for the WikipediaA Content-Driven Reputation System for the Wikipedia
A Content-Driven Reputation System for the Wikipedia
 
SVD review
SVD reviewSVD review
SVD review
 
Mongrel Handlers
Mongrel HandlersMongrel Handlers
Mongrel Handlers
 
Blue Ocean Strategy
Blue Ocean StrategyBlue Ocean Strategy
Blue Ocean Strategy
 
日本7-ELEVEN消費心理學
日本7-ELEVEN消費心理學日本7-ELEVEN消費心理學
日本7-ELEVEN消費心理學
 
Comparing State-of-the-Art Collaborative Filtering Systems
Comparing State-of-the-Art Collaborative Filtering SystemsComparing State-of-the-Art Collaborative Filtering Systems
Comparing State-of-the-Art Collaborative Filtering Systems
 
Item Based Collaborative Filtering Recommendation Algorithms
Item Based Collaborative Filtering Recommendation AlgorithmsItem Based Collaborative Filtering Recommendation Algorithms
Item Based Collaborative Filtering Recommendation Algorithms
 
Agile Adoption2007
Agile Adoption2007Agile Adoption2007
Agile Adoption2007
 
Modern Compiler Design
Modern Compiler DesignModern Compiler Design
Modern Compiler Design
 
透过众神的眼睛--鸟瞰非洲
透过众神的眼睛--鸟瞰非洲透过众神的眼睛--鸟瞰非洲
透过众神的眼睛--鸟瞰非洲
 
Improving Quality of Search Results Clustering with Approximate Matrix Factor...
Improving Quality of Search Results Clustering with Approximate Matrix Factor...Improving Quality of Search Results Clustering with Approximate Matrix Factor...
Improving Quality of Search Results Clustering with Approximate Matrix Factor...
 
Support Vector Machines
Support Vector MachinesSupport Vector Machines
Support Vector Machines
 
Bigtable
BigtableBigtable
Bigtable
 

Recently uploaded

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

Nio

  • 1. http://gee.cs.oswego.edu Scalable IO in Java Doug Lea State University of New York at Oswego dl@cs.oswego.edu http://gee.cs.oswego.edu
  • 2. Outline Scalable network services quot; http://gee.cs.oswego.edu Event-driven processing quot; Reactor pattern quot; Basic version Multithreaded versions Other variants Walkthrough of java.nio nonblocking IO APIs quot;
  • 3. Network Services Web services, Distributed Objects, etc quot; http://gee.cs.oswego.edu Most have same basic structure: quot; Read request Decode request Process service Encode reply Send reply But differ in nature and cost of each step quot; XML parsing, File transfer, Web page generation, computational services, ...
  • 4. Classic Service Designs http://gee.cs.oswego.edu decode compute encode send read client handler decode compute encode send read client Server handler decode compute encode send read client handler Each handler may be started in its own thread
  • 5. Classic ServerSocket Loop class Server implements Runnable { public void run() { try { http://gee.cs.oswego.edu ServerSocket ss = new ServerSocket(PORT); while (!Thread.interrupted()) new Thread(new Handler(ss.accept())).start(); // or, single-threaded, or a thread pool } catch (IOException ex) { /* ... */ } } static class Handler implements Runnable { final Socket socket; Handler(Socket s) { socket = s; } public void run() { try { byte[] input = new byte[MAX_INPUT]; socket.getInputStream().read(input); byte[] output = process(input); socket.getOutputStream().write(output); } catch (IOException ex) { /* ... */ } } private byte[] process(byte[] cmd) { /* ... */ } } } Note: most exception handling elided from code examples
  • 6. Scalability Goals Graceful degradation under increasing load quot; http://gee.cs.oswego.edu (more clients) Continuous improvement with increasing quot; resources (CPU, memory, disk, bandwidth) Also meet availability and performance goals quot; Short latencies Meeting peak demand Tunable quality of service Divide-and-conquer is usually the best quot; approach for achieving any scalability goal
  • 7. Divide and Conquer Divide processing into small tasks quot; http://gee.cs.oswego.edu Each task performs an action without blocking Execute each task when it is enabled quot; Here, an IO event usually serves as trigger decode compute encode send read handler Basic mechanisms supported in java.nio quot; Non-blocking reads and writes Dispatch tasks associated with sensed IO events Endless variation possible quot; A family of event-driven designs
  • 8. Event-driven Designs Usually more efficient than alternatives quot; http://gee.cs.oswego.edu Fewer resources Don't usually need a thread per client quot; Less overhead Less context switching, often less locking quot; But dispatching can be slower Must manually bind actions to events quot; Usually harder to program quot; Must break up into simple non-blocking actions Similar to GUI event-driven actions quot; Cannot eliminate all blocking: GC, page faults, etc quot; Must keep track of logical state of service
  • 9. Background: Events in AWT AWT Event Queue http://gee.cs.oswego.edu Event ... Button Event AWT thread click! ActionListener public void actionPerformed(...) { doSomething(); } Event-driven IO uses similar ideas but in different designs
  • 10. Reactor Pattern Reactor responds to IO events by dispatching quot; the appropriate handler http://gee.cs.oswego.edu Similar to AWT thread Handlers perform non-blocking actions quot; Similar to AWT ActionListeners Manage by binding handlers to events quot; Similar to AWT addActionListener See Schmidt et al, Pattern-Oriented Software quot; Architecture, Volume 2 (POSA2) Also Richard Stevens's networking books, Matt Welsh's SEDA framework, etc
  • 11. Basic Reactor Design http://gee.cs.oswego.edu Reactor client dispatch client decode compute encode send read decode compute encode send read client decode compute encode send acceptor read Single threaded version
  • 12. java.nio Support Channels quot; http://gee.cs.oswego.edu Connections to files, sockets etc that support non-blocking reads Buffers quot; Array-like objects that can be directly read or written by Channels Selectors quot; Tell which of a set of Channels have IO events SelectionKeys quot; Maintain IO event status and bindings
  • 13. Reactor 1: Setup class Reactor implements Runnable { final Selector selector; final ServerSocketChannel serverSocket; http://gee.cs.oswego.edu Reactor(int port) throws IOException { selector = Selector.open(); serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind( new InetSocketAddress(port)); serverSocket.configureBlocking(false); SelectionKey sk = serverSocket.register(selector, SelectionKey.OP_ACCEPT); sk.attach(new Acceptor()); } /* Alternatively, use explicit SPI provider: SelectorProvider p = SelectorProvider.provider(); selector = p.openSelector(); serverSocket = p.openServerSocketChannel(); */
  • 14. Reactor 2: Dispatch Loop // class Reactor continued public void run() { // normally in a new Thread http://gee.cs.oswego.edu try { while (!Thread.interrupted()) { selector.select(); Set selected = selector.selectedKeys(); Iterator it = selected.iterator(); while (it.hasNext()) dispatch((SelectionKey)(it.next()); selected.clear(); } } catch (IOException ex) { /* ... */ } } void dispatch(SelectionKey k) { Runnable r = (Runnable)(k.attachment()); if (r != null) r.run(); }
  • 15. Reactor 3: Acceptor // class Reactor continued class Acceptor implements Runnable { // inner http://gee.cs.oswego.edu public void run() { try { SocketChannel c = serverSocket.accept(); if (c != null) new Handler(selector, c); } catch(IOException ex) { /* ... */ } } } } Reactor client dispatch client decode compute encode send read decode compute encode send read client decode compute encode send acceptor read
  • 16. Reactor 4: Handler setup final class Handler implements Runnable { final SocketChannel socket; final SelectionKey sk; http://gee.cs.oswego.edu ByteBuffer input = ByteBuffer.allocate(MAXIN); ByteBuffer output = ByteBuffer.allocate(MAXOUT); static final int READING = 0, SENDING = 1; int state = READING; Handler(Selector sel, SocketChannel c) throws IOException { socket = c; c.configureBlocking(false); // Optionally try first read now sk = socket.register(sel, 0); sk.attach(this); sk.interestOps(SelectionKey.OP_READ); sel.wakeup(); } boolean inputIsComplete() { /* ... */ } boolean outputIsComplete() { /* ... */ } void process() { /* ... */ }
  • 17. Reactor 5: Request handling // class Handler continued public void run() { try { http://gee.cs.oswego.edu if (state == READING) read(); else if (state == SENDING) send(); } catch (IOException ex) { /* ... */ } } void read() throws IOException { socket.read(input); if (inputIsComplete()) { process(); state = SENDING; // Normally also do first write now sk.interestOps(SelectionKey.OP_WRITE); } } void send() throws IOException { socket.write(output); if (outputIsComplete()) sk.cancel(); } }
  • 18. Per-State Handlers A simple use of GoF State-Object pattern quot; http://gee.cs.oswego.edu Rebind appropriate handler as attachment class Handler { // ... public void run() { // initial state is reader socket.read(input); if (inputIsComplete()) { process(); sk.attach(new Sender()); sk.interest(SelectionKey.OP_WRITE); sk.selector().wakeup(); } } class Sender implements Runnable { public void run(){ // ... socket.write(output); if (outputIsComplete()) sk.cancel(); } } }
  • 19. Multithreaded Designs Strategically add threads for scalability quot; Mainly applicable to multiprocessors http://gee.cs.oswego.edu Worker Threads quot; Reactors should quickly trigger handlers Handler processing slows down Reactor quot; Offload non-IO processing to other threads Multiple Reactor Threads quot; Reactor threads can saturate doing IO Distribute load to other reactors Load-balance to match CPU and IO rates quot;
  • 20. Worker Threads Offload non-IO processing to speed up quot; Reactor thread http://gee.cs.oswego.edu Similar to POSA2 Proactor designs Simpler than reworking compute-bound quot; processing into event-driven form Should still be pure nonblocking computation Enough processing to outweigh overhead quot; But harder to overlap processing with IO quot; Best when can first read all input into a buffer Use thread pool so can tune and control quot; Normally need many fewer threads than clients
  • 21. Worker Thread Pools client Reactor http://gee.cs.oswego.edu client send read send read acceptor client send read decode compute encode worker Thread threads Pool decode compute encode decode compute encode queued tasks
  • 22. Handler with Thread Pool class Handler implements Runnable { // uses util.concurrent thread pool static PooledExecutor pool = new PooledExecutor(...); http://gee.cs.oswego.edu static final int PROCESSING = 3; // ... synchronized void read() { // ... socket.read(input); if (inputIsComplete()) { state = PROCESSING; pool.execute(new Processer()); } } synchronized void processAndHandOff() { process(); state = SENDING; // or rebind attachment sk.interest(SelectionKey.OP_WRITE); } class Processer implements Runnable { public void run() { processAndHandOff(); } } }
  • 23. Coordinating Tasks Handoffs quot; Each task enables, triggers, or calls next one http://gee.cs.oswego.edu Usually fastest but can be brittle Callbacks to per-handler dispatcher quot; Sets state, attachment, etc A variant of GoF Mediator pattern Queues quot; For example, passing buffers across stages Futures quot; When each task produces a result Coordination layered on top of join or wait/notify
  • 24. Using PooledExecutor A tunable worker thread pool quot; Main method execute(Runnable r) http://gee.cs.oswego.edu quot; Controls for: quot; The kind of task queue (any Channel) Maximum number of threads Minimum number of threads quot;Warmquot; versus on-demand threads Keep-alive interval until idle threads die to be later replaced by new ones if necessary quot; Saturation policy block, drop, producer-runs, etc quot;
  • 25. Multiple Reactor Threads Using Reactor Pools quot; http://gee.cs.oswego.edu Use to match CPU and IO rates Static or dynamic construction Each with own Selector, Thread, dispatch loop quot; Main acceptor distributes to other reactors Selector[] selectors; // also create threads int next = 0; class Acceptor { // ... public synchronized void run() { ... Socket connection = serverSocket.accept(); if (connection != null) new Handler(selectors[next], connection); if (++next == selectors.length) next = 0; } }
  • 26. Using Multiple Reactors client mainReactor subReactor http://gee.cs.oswego.edu client send read send read acceptor client send read decode compute encode worker Thread threads Pool decode compute encode decode compute encode queued tasks
  • 27. Using other java.nio features Multiple Selectors per Reactor quot; To bind different handlers to different IO events http://gee.cs.oswego.edu May need careful synchronization to coordinate File transfer quot; Automated file-to-net or net-to-file copying Memory-mapped files quot; Access files via buffers Direct buffers quot; Can sometimes achieve zero-copy transfer But have setup and finalization overhead Best for applications with long-lived connections
  • 28. Connection-Based Extensions Instead of a single service request, quot; http://gee.cs.oswego.edu Client connects Client sends a series of messages/requests Client disconnects Examples quot; Databases and Transaction monitors Multi-participant games, chat, etc Can extend basic network service patterns quot; Handle many relatively long-lived clients Track client and session state (including drops) Distribute services across multiple hosts
  • 29. API Walkthrough Buffer quot; http://gee.cs.oswego.edu ByteBuffer quot; (CharBuffer, LongBuffer, etc not shown.) Channel quot; SelectableChannel quot; SocketChannel quot; ServerSocketChannel quot; FileChannel quot; Selector quot; SelectionKey quot;
  • 30. Buffer abstract class Buffer { int capacity(); int position(); http://gee.cs.oswego.edu Buffer position(int newPosition); int limit(); Buffer limit(int newLimit); Buffer mark(); Buffer reset(); Buffer clear(); Buffer flip(); Buffer rewind(); int remaining(); boolean hasRemaining(); boolean isReadOnly(); } abc position limit capacity mark
  • 31. ByteBuffer (1) abstract class ByteBuffer extends Buffer { static ByteBuffer allocateDirect(int capacity); static ByteBuffer allocate(int capacity); http://gee.cs.oswego.edu static ByteBuffer wrap(byte[] src, int offset, int len); static ByteBuffer wrap(byte[] src); boolean isDirect(); ByteOrder order(); ByteBuffer order(ByteOrder bo); ByteBuffer slice(); ByteBuffer duplicate(); ByteBuffer compact(); ByteBuffer asReadOnlyBuffer(); byte get(); byte get(int index); ByteBuffer get(byte[] dst, int offset, int length); ByteBuffer get(byte[] dst); ByteBuffer put(byte b); ByteBuffer put(int index, byte b); ByteBuffer put(byte[] src, int offset, int length); ByteBuffer put(ByteBuffer src); ByteBuffer put(byte[] src); char getChar(); char getChar(int index); ByteBuffer putChar(char value); ByteBuffer putChar(int index, char value); CharBuffer asCharBuffer();
  • 32. ByteBuffer (2) short getShort(); short getShort(int index); ByteBuffer putShort(short value); http://gee.cs.oswego.edu ByteBuffer putShort(int index, short value); ShortBuffer asShortBuffer(); int getInt(); int getInt(int index); ByteBuffer putInt(int value); ByteBuffer putInt(int index, int value); IntBuffer asIntBuffer(); long getLong(); long getLong(int index); ByteBuffer putLong(long value); ByteBuffer putLong(int index, long value); LongBuffer asLongBuffer(); float getFloat(); float getFloat(int index); ByteBuffer putFloat(float value); ByteBuffer putFloat(int index, float value); FloatBuffer asFloatBuffer(); double getDouble(); double getDouble(int index); ByteBuffer putDouble(double value); ByteBuffer putDouble(int index, double value); DoubleBuffer asDoubleBuffer(); }
  • 33. Channel interface Channel { boolean isOpen(); void close() throws IOException; http://gee.cs.oswego.edu } interface ReadableByteChannel extends Channel { int read(ByteBuffer dst) throws IOException; } interface WritableByteChannel extends Channel { int write(ByteBuffer src) throws IOException; } interface ScatteringByteChannel extends ReadableByteChannel { int read(ByteBuffer[] dsts, int offset, int length) throws IOException; int read(ByteBuffer[] dsts) throws IOException; } interface GatheringByteChannel extends WritableByteChannel { int write(ByteBuffer[] srcs, int offset, int length) throws IOException; int write(ByteBuffer[] srcs) throws IOException; }
  • 34. SelectableChannel abstract class SelectableChannel implements Channel { int validOps(); http://gee.cs.oswego.edu boolean isRegistered(); SelectionKey keyFor(Selector sel); SelectionKey register(Selector sel, int ops) throws ClosedChannelException; void configureBlocking(boolean block) throws IOException; boolean isBlocking(); Object blockingLock(); }
  • 35. SocketChannel abstract class SocketChannel implements ByteChannel ... { static SocketChannel open() throws IOException; http://gee.cs.oswego.edu Socket socket(); int validOps(); boolean isConnected(); boolean isConnectionPending(); boolean isInputOpen(); boolean isOutputOpen(); boolean connect(SocketAddress remote) throws IOException; boolean finishConnect() throws IOException; void shutdownInput() throws IOException; void shutdownOutput() throws IOException; int read(ByteBuffer dst) throws IOException; int read(ByteBuffer[] dsts, int offset, int length) throws IOException; int read(ByteBuffer[] dsts) throws IOException; int write(ByteBuffer src) throws IOException; int write(ByteBuffer[] srcs, int offset, int length) throws IOException; int write(ByteBuffer[] srcs) throws IOException; }
  • 36. ServerSocketChannel abstract class ServerSocketChannel extends ... { static ServerSocketChannel open() throws IOException; http://gee.cs.oswego.edu int validOps(); ServerSocket socket(); SocketChannel accept() throws IOException; }
  • 37. FileChannel abstract class FileChannel implements ... { int read(ByteBuffer dst); int read(ByteBuffer dst, long position); http://gee.cs.oswego.edu int read(ByteBuffer[] dsts, int offset, int length); int read(ByteBuffer[] dsts); int write(ByteBuffer src); int write(ByteBuffer src, long position); int write(ByteBuffer[] srcs, int offset, int length); int write(ByteBuffer[] srcs); long position(); void position(long newPosition); long size(); void truncate(long size); void force(boolean flushMetaDataToo); int transferTo(long position, int count, WritableByteChannel dst); int transferFrom(ReadableByteChannel src, long position, int count); FileLock lock(long position, long size, boolean shared); FileLock lock(); FileLock tryLock(long pos, long size, boolean shared); FileLock tryLock(); static final int MAP_RO, MAP_RW, MAP_COW; MappedByteBuffer map(int mode, long position, int size); } NOTE: ALL methods throw IOException
  • 38. Selector abstract class Selector { static Selector open() throws IOException; Set keys(); http://gee.cs.oswego.edu Set selectedKeys(); int selectNow() throws IOException; int select(long timeout) throws IOException; int select() throws IOException; void wakeup(); void close() throws IOException; }
  • 39. SelectionKey abstract class SelectionKey { static final int OP_READ, OP_WRITE, OP_CONNECT, OP_ACCEPT; http://gee.cs.oswego.edu SelectableChannel channel(); Selector selector(); boolean isValid(); void cancel(); int interestOps(); void interestOps(int ops); int readyOps(); boolean isReadable(); boolean isWritable(); boolean isConnectable(); boolean isAcceptable(); Object attach(Object ob); Object attachment(); }