System Programming Practical session 12 Reactor.

Slides:



Advertisements
Similar presentations
Practical Session 6 Multitasking vs. multithreading Threads Concurrency vs. Parallelism Java Threads Thread confinement Object/Class Immutability.
Advertisements

SOCKET PROGRAMMING WITH MOBILE SOCKET CLIENT DEARTMENT OF COMPUTER SCIENCE IOWA STATE UNIVERSITY.
Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Andrew Borg. The University of York. 1 Java NIO Andrew Borg.
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
Java Threads A tool for concurrency. OS schedules processes Ready Running 200 Blocked A process loses the CPU and another.
1 Java Networking – Part I CS , Spring 2008/9.
Precept 3 COS 461. Concurrency is Useful Multi Processor/Core Multiple Inputs Don’t wait on slow devices.
Server Architecture Models Operating Systems Hebrew University Spring 2004.
System Programming Practical session 10 Java sockets.
System Programming Practical session 11 Multiple clients server Non-Blocking I/O.
© Lethbridge/Laganière 2001 Chap. 3: Basing Development on Reusable Technology 1 Let’s get started. Let’s start by selecting an architecture from among.
An Introduction to Internetworking. Algorithm for client-server communication with UDP (connectionless) A SERVER A CLIENT Create a server-socket (listener)and.
Scalable network services - Java non-blocking IO - Reactor pattern
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
Java Metroplex User's Group
Practical Session 11 Multi Client-Server Java NIO.
 George Chrysanthakopoulos Software Architect Microsoft Corporation.
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
Java NIO. NIO: New I/O Prior to the J2SE 1.4 release of Java, I/O had become a bottleneck. –JIT performance was reaching the point where one could start.
CS 352-Socket Programming & Threads Dept. of Computer Science Rutgers University (Thanks,this slides taken from er06/
Programming Network Servers Topic 6, Chapters 21, 22 Network Programming Kansas State University at Salina.
Apache Mina Dima Ionut Daniel. Contents What is Apache Mina? Why Apache Mina? Mina Architecture Mina Core Mina Advanced JMX Support Spring Integration.
Cli/Serv.: Chat/121 Client/Server Distributed Systems v Objectives –discuss a client/server based chat system –mention two other ways of chatting.
© 2009 by Eike Stepper; made available under the EPL v1.0 | The Net4j Signalling Platform Developing Pluggable Client/Server Applications Eike.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 22.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Networking and Concurrency COMP.
Dynamic Architectures (Component Reconfiguration) with Fractal.
Practical Session 12 Reactor Pattern. Disadvantages of Thread per Client It's wasteful – Creating a new Thread is relatively expensive. – Each thread.
Java for High Performance Computing java.nio: High Performance I/O for Java Instructor: Bryan Carpenter.
CSC 480 Software Engineering Socket. What is Socket? A socket is one end-point of a two-way communication link between two programs running on the network.
Practical Session 11 Multi Client-Server Java NIO.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Architectural pattern: Reactor Source: POSA II pp 179 – 214POSA II Environment: an application that receives multiple requests simultaneously but may process.
E81 CSE 532S: Advanced Multi-Paradigm Software Development Venkita Subramonian, Christopher Gill, Ying Huang, Marc Sentany Department of Computer Science.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
Distributed Systems CS Project 1: File Storage and Access Kit (FileStack) Recitation 1, Aug 29, 2013 Dania Abed Rabbou and Mohammad Hammoud.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
I/O Multiplexing Chap 6. I/O Models  Blocking I/O Model  Nonblocking I/O Model  I/O Multiplexing Model  Signal Driven I/O Model  Asynchronous I/O.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Advanced Java Session 4 - Extra New York University School of Continuing and Professional Studies.
Li Tak Sing COMPS311F. Case study: a multithreaded chat server The source contains 3 files: ChatServer //the chat server ChatThread //the thread on the.
Network Applications: High-performance Server Design: Async Servers/Operational Analysis Y. Richard Yang 2/24/2016.
SPL/2010 Reactor Design Pattern 1. SPL/2010 Overview ● blocking sockets - impact on server scalability. ● non-blocking IO in Java - java.niopackage ●
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Lecture 6 Threads Erick Pranata
Threads in Java Two ways to start a thread
Thread Pools (Worker Queues) cs
Thread Pools (Worker Queues) cs
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Client-server Programming
Network Applications: High-performance Server Design & Operational Analysis Y. Richard Yang 10/5/2017.
Netty.
Threads II IS
Implementation CAN Communication Engine
Reactor Design Pattern
Application Protocols
Y. Richard Yang 10/9/2018 Network Applications: High-Performance Server Design (Async Select NonBlocking Servers)
The reactor design pattern
Thread per client and Java NIO
Presentation transcript:

System Programming Practical session 12 Reactor

Thread-Per-Client downsides Each thread waste resources. Blocking I/O. Vulnerability to denial of service attack. The Reactor design pattern solve these problems. One thread deals with communication. Fixed number of threads deal with work. communication and work layers are separate and asynchronous. Non-blocking I/O.

Non-Blocking I/O Server ConnectionAcceptor ServerSocketChannel key Selector ConnectionAcceptor ServerSocketChannel SocketChannel ConnectionHandler SocketChannel SocketChannel ProtocolTask SocketChannel

Channels Channels wrap sockets, and allow non-blocking I/O. read(), write() , accept() can be non blocking. Setting up a non-blocking ServerSocketChannel listening on a specific port. int port = 9999; ServerSocketChannel ssChannel = serverSocketChannel.open(); ssChannel.configureBlocking(false); ssChannel.socket().bind(new InetSocketAddress(port));

Buffers ByteBuffer are buffers that hold bytes. Channels know how to read and write to buffers. Creating a Buffer final int NUM_OF_BYTES = 1024; ByteBuffer buf = ByteBuffer.allocate(NUM_OF_BYTES); From Channel to Buffer and back numBytesRead = _socketChannel.read(buf1); numBytesWritten = _socketChannel.write(buf2); Return –1 if channel is closed. Update position marker of the buffer.

Selector The selector monitors the channels for new events (new data arrived, new connection). A Selector is registered to each channel with an attachment to handle the event. An appropriate attachment is invoked for each new event. Selector selector = Selector.open(); Object anAttachment = new Object(); socketChannel.register(selector, SelectionKey.OP_READ, anAttachmemt);

select() Method selector.select(); Blocks until at least one of the channels is ready for the registered event. A list of SelectionKeys is returned. Each Selectionkey is associated with one event, and holds the attachment registered with the event.

Reactor Actors Reactor – The main class. Creates ServerSocket channel Registers the Selector For each event, invokes the appropriate attachment ConnectionAcceptor ConnectionHandler

Reactor Actors ConnectionAcceptor accept() Creates SocketChanel. Register the Selector. Creates ConnectionHandler.

Reactor Actors ConnectionHandler Read() Reads new data from channel. Adds ProtoclTask for yet unprocessed input data to a fixed thread pool. Write() Receives output data from ProtocolTask. Writes the data to the channel.

Reactor Actors ProtocolTask Passes unprocessed input data to message tokenizer. Processes each complete message. Passes output data to ConnectionHandler.

Execution example ssChannel selector executor public class Reactor{ ... selector ssChannel ServerSocketChannel ssChannel = ServerSocketChannel.open(); ssChannel.configureBlocking( false); ssChannel.socket().bind(new InetSocketAddress(port)); Selector selector = Selector.open(); ssChannel.register(selector, SelectionKey.OP_ACCEPT, connectionAcceptor);  ExecutorService executor =  Executors.newFixedThreadPool( _poolSize); executor

while (_shouldRun && selector.isOpen()) { try { selector.select(); } catch (IOException e) {…} Iterator it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); it.remove(); if (selKey.isValid() && selKey.isAcceptable()) { ConnectionAcceptor acceptor = (ConnectionAcceptor) selKey.attachment(); acceptor.accept(); } catch (IOException e) {…) if (selKey.isValid() && selKey.isReadable()) { //Handle reading… } if (selKey.isValid() && selKey.isWritable()) { //Handle writing… } }

ssChannel selector sChannel sChannel sChannel public class ConnectionAcceptor { … public void accept() { SocketChannel sChannel = _ssChannel.accept(); if (sChannel != null) { sChannel.configureBlocking(false); SelectionKey key =sChannel.register( _data.getSelector(), 0); ConnectionHandler handler = ConnectionHandler.create(sChannel, _data, key); handler.switchToReadOnlyMode();} } Client connection request selector ssChannel sChannel sChannel sChannel

selector ssChannel “Don’t worry” sChannel sChannel sChannel

while (_shouldRun && selector.isOpen()) { try { selector.select(); } catch (IOException e) {…} Iterator it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); it.remove(); if (selKey.isValid() && selKey.isAcceptable()) { … } if (selKey.isValid() && selKey.isReadable()) { ConnectionHandler handler = (ConnectionHandler) selKey.attachment(); handler.read(); } if (selKey.isValid() && selKey.isWritable()) { //Handle writing… }

ssChannel selector “Don’t worry” sChannel sChannel sChannel public class ConnectionHandler {… public void read() { ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE); int numBytesRead = 0; try { numBytesRead =sChannel.read(buf); } catch (IOException e) { numBytesRead = -1; } if (numBytesRead == -1) { closeConnection(); _protocol.connectionTerminated(); return; } buf.flip(); _task.addBytes(buf); _data.getExecutor().execute(_task); selector ssChannel “Don’t worry” sChannel sChannel sChannel

_buffers public class ProtocolTask implements Runnable { private final Vector<ByteBuffer> _buffers = new Vector<ByteBuffer>(); … public synchronized void run() { synchronized (_buffers) { while(_buffers.size() > 0) { ByteBuffer buf = _buffers.remove(0); this._tokenizer.addBytes(buf); } } while (_tokenizer.hasMessage()) { public void addBytes(ByteBuffer b) { _buffers.add(b); _buffers

_tokenizer “Don’t worry” _buffers D o n ’ t w o r r y public class ProtocolTask implements Runnable { private final Vector<ByteBuffer> _buffers = new Vector<ByteBuffer>(); … public synchronized void run() { synchronized (_buffers) { while(_buffers.size() > 0) { ByteBuffer buf = _buffers.remove(0); this._tokenizer.addBytes(buf); } } while (_tokenizer.hasMessage()) { public void addBytes(ByteBuffer b) { _buffers.add(b); _tokenizer “Don’t worry” _buffers D o n ’ t w o r r y

ssChannel selector “be happy\n” sChannel sChannel sChannel public class ConnectionHandler {… public void read() { ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE); int numBytesRead = 0; try { numBytesRead =sChannel.read(buf); } catch (IOException e) { numBytesRead = -1; } if (numBytesRead == -1) { closeConnection(); _protocol.connectionTerminated(); return; } buf.flip(); _task.addBytes(buf); _data.getExecutor().execute(_task); selector ssChannel “be happy\n” sChannel sChannel sChannel

“Don’t worry be happy\n” public class ProtocolTask implements Runnable {… … public synchronized void run() { synchronized (_buffers) { while(_buffers.size() > 0) { ByteBuffer buf = _buffers.remove(0); this._tokenizer.addBytes(buf); } } while (_tokenizer.hasMessage()) { String msg = _tokenizer.nextMessage(); String response = this._protocol.processMessage(msg); if (response != null) { try { ByteBuffer bytes = _tokenizer.getBytesForMessage(response); this._handler.addOutData(bytes); } catch (CharacterCodingException e) { … } } } } public void addBytes(ByteBuffer b) { synchronized (_buffers) { _buffers.add(b); } } _tokenizer “Don’t worry be happy\n” response “Your message “Don’t worry be happy” received”

public class ConnectionHandler{ … public synchronized void addOutData(ByteBuffer buf) { _outData.add(buf); switchToReadWriteMode(); } public void switchToReadWriteMode() { _skey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); _data.getSelector().wakeup();

selector ssChannel sChannel sChannel sChannel

while (_shouldRun && selector.isOpen()) { try { selector.select(); } catch (IOException e) {…} Iterator it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); it.remove(); if (selKey.isValid() && selKey.isAcceptable()) { … } if (selKey.isValid() && selKey.isReadable()){…} if (selKey.isValid() && selKey.isWritable()){ ConnectionHandler handler = (ConnectionHandler) selKey.attachment(); handler.write(); }

ssChannel selector sChannel sChannel sChannel public synchronized void write() { if (_outData.size() == 0) { switchToReadOnlyMode(); return; } ByteBuffer buf = _outData.remove(0); if (buf.remaining() != 0) { try { _sChannel.write(buf); } catch (IOException e) {…} _outData.add(0, buf); } } if (_protocol.shouldClose()) { switchToWriteOnlyMode(); if (buf.remaining() == 0) { closeConnection(); ssChannel selector “Your message “Don’t worry be happy” received” sChannel sChannel sChannel

ssChannel selector sChannel sChannel public synchronized void write() { if (_outData.size() == 0) { switchToReadOnlyMode(); return; } ByteBuffer buf = _outData.remove(0); if (buf.remaining() != 0) { try { _sChannel.write(buf); } catch (IOException e) {…} _outData.add(0, buf); } } if (_protocol.shouldClose()) { switchToWriteOnlyMode(); if (buf.remaining() == 0) { closeConnection(); ssChannel selector sChannel sChannel