Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java NIO.2

1,776 views

Published on

The latest slide deck about Java NIO.2 from *instinctools Java developer Alexandr Brui. You can find here Java NIO.2 design, work with data, selector & channels, reading & writing and many more.

Published in: Software
  • Be the first to comment

Java NIO.2

  1. 1. Java NIO.2
  2. 2. Network socket Network socket is an endpoint of a connection across a computer network. Main types of Internet socket: ● Datagram sockets, which use User Datagram Protocol (UDP). ● Stream sockets, which use Transmission Control Protocol (TCP) or Stream Control Transmission Protocol (SCTP). ● Raw sockets, typically available in routers and other network equipment.
  3. 3. Java IO vs NIO IO NIO Stream-oriented Buffer-oriented Blocking I/O Non-blocking I/O Selectors Channels
  4. 4. Java.IO - Stream-oriented Data Source Program Data Destination Program 001001001111001001001001011 001001001111001001001001011
  5. 5. Java.IO - Blocking I/O Socket Thread read data, block until ready read data, block until ready write data, block until ready write data, block until ready
  6. 6. Java.IO — Work with data // read from socket Scanner sc = new Scanner(socket.getInputStream()); String string = sc.nextLine(); System.out.println("Received " + string); // write to socket PrintWriter pw = new PrintWriter(socket.getOutputStream()); pw.println("Hello");
  7. 7. Java.NIO — Buffer-oriented & Non-blocking I/O Channel Buffer Thread read data into buffer fill data into buffer check data in buffer goto top
  8. 8. Java.NIO — Work with data ByteBuffer readBuffer = ByteBuffer.allocate(1024); // prepare to read readBuffer.clear(); SocketChannel channel = getChannel(); channel.read(readBuffer); readBuffer.flip(); // reading the buffer // ...............… ByteBuffer writeBuffer = ByteBuffer.allocate(1024); // prepare to put data writeBuffer.clear(); // putting the data // ............... // prepare to write writeBuffer.flip(); channel.write(writeBuffer);
  9. 9. Java.NIO — Selector & Channels Channel is a lightweight entity effeciently transporting data between sockets as a tube. Selector is a manager allowing a single thread to monitor multiple input channels.
  10. 10. Java.IO - Classic IO server design Server Socket Thread Connection Thread Connection Thread Connection Thread Connection Thread
  11. 11. Java.NIO — NIO server design Thread Selector Channel Channel Channel Channel
  12. 12. Java.NIO — NIO server design ServerSocketChannel channel = ServerSocketChannel.open(); channel.bind(new InetSocketAddress("localhost", 2222)); channel.configureBlocking(false); Selector selector = Selector.open(); SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT); while (true) { if (selector.select() == 0) { Thread.sleep(1); continue; } Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey selectionKey = keyIterator.next(); if (selectionKey.isAcceptable()) { // a connection was accepted by a ServerSocketChannel. } else if (selectionKey.isConnectable()) { // a connection was established with a remote. } else if (selectionKey.isReadable()) { // a channel is ready for reading } else if (selectionKey.isWritable()) { // a channel is ready for writing } keyIterator.remove(); } }
  13. 13. Java NIO.1 vs NIO.2 NIO.1 NIO.2 Selector AsynchronousChannelGroup ServerSocketChannel AsynchronousServerSocketChannel SocketChannel AsynchronousSocketChannel SelectionKey CompletionHandler
  14. 14. Java.NIO.2 — Reading ByteBuffer readBuffer = ByteBuffer.allocate(1024); // prepare to read readBuffer.clear(); AsynchronousSocketChannel channel = getChannel2(); channel.read(readBuffer, null, new CompletionHandler<Integer, Object>() { @Override public void completed(Integer result, Object attachment) { // buffer is ready for read } @Override public void failed(Throwable exc, Object attachment) { exc.printStackTrace(); } });
  15. 15. Java.NIO.2 — Writing ByteBuffer writeBuffer = ByteBuffer.allocate(1024); // prepare to put data writeBuffer.clear(); // putting data // ............... // prepare to write writeBuffer.flip(); AsynchronousSocketChannel channel = getChannel2(); channel.write(writeBuffer, null, new CompletionHandler<Integer, Object>() { @Override public void completed(Integer result, Object attachment) { // writing has been completed } @Override public void failed(Throwable exc, Object attachment) { exc.printStackTrace(); } });
  16. 16. Java.NIO — NIO.1 server design ServerSocketChannel channel = ServerSocketChannel.open(); channel.bind(new InetSocketAddress("localhost", 2222)); channel.configureBlocking(false); Selector selector = Selector.open(); SelectionKey key = channel.register(selector, SelectionKey.OP_ACCEPT); while (true) { if (selector.select() == 0) { Thread.sleep(1); continue; } Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey selectionKey = keyIterator.next(); if (selectionKey.isAcceptable()) { // a connection was accepted by a ServerSocketChannel. } else if (selectionKey.isConnectable()) { // a connection was established with a remote. } else if (selectionKey.isReadable()) { // a channel is ready for reading } else if (selectionKey.isWritable()) { // a channel is ready for writing } keyIterator.remove(); } }
  17. 17. Java.NIO — NIO.2 server design AsynchronousChannelGroup group = AsynchronousChannelGroup.withThreadPool(newFixedThreadPool(10)); AsynchronousServerSocketChannel channel = open(group); channel.bind(new InetSocketAddress("localhost", 2222)); channel.accept(null, toHandler((client, attach) -> { ByteBuffer readBuffer = ByteBuffer.allocate(1024); ByteBuffer writeBuffer = ByteBuffer.allocate(1024); client.read(readBuffer, null, toHandler((result, attachment) -> { // buffer is ready for read })); client.write(writeBuffer, null, toHandler((result, attachment) -> { // writing has been completed })); }));
  18. 18. public class NetworkServer { AsynchronousServerSocketChannel channel; CompletionHandler<AsynchronousSocketChannel, Void> handler; public NetworkServer(SocketAddress address) throws IOException { AsynchronousChannelGroup group = withFixedThreadPool(10, Thread::new); handler = toHandler((channel, attach) -> processAccept(channel)); channel = AsynchronousServerSocketChannel.open(group); channel.bind(address); channel.accept(null, toHandler((clientChannel, attach) -> processAccept(clientChannel))); } private void processAccept(AsynchronousSocketChannel clientChannel) { NetworkClient networkClient = new NetworkClient(clientChannel, message -> out.println("Server: received: " + message)); networkClient.write("Hello! I'm NIO.2 server!n"); channel.accept(null, handler); } public void stop() throws IOException { channel.close(); } } Java NIO.2 — Basic implementation of server
  19. 19. public class NetworkClient { AtomicBoolean isWriting = new AtomicBoolean(); Deque<String> toWrite = new ConcurrentLinkedDeque<>(); Consumer<String> readFunction; CompletionHandler<Integer, ByteBuffer> readHandler = toHandler((byteCount, buffer) -> finishRead(byteCount)); CompletionHandler<Integer, ByteBuffer> writeHandler = toHandler((byteCount, buffer) -> finishWrite()); ByteBuffer rb = allocateDirect(1024); ByteBuffer wb = allocateDirect(1024); AsynchronousSocketChannel channel; public NetworkClient(AsynchronousSocketChannel channel, Consumer<String> readFunction) { this.channel = channel; this.readFunction = readFunction; readNext(); } private void finishRead(Integer byteCount) { if(byteCount.equals(-1)) return; readFunction.accept(NUtils.read(rb)); readNext(); } private void finishWrite() { if (isWriting.compareAndSet(true, false)) writeNext(); } public void write(String message) { toWrite.add(message); if(isWriting.compareAndSet(false, true)) writeNext(); } private void writeNext() { if(toWrite.isEmpty()) return; NUtils.write(wb, toWrite); channel.write(wb, wb, writeHandler); } private void readNext() { channel.read(rb, rb, readHandler); } } Java NIO.2 — Basic implementation of server
  20. 20. new Thread(run(() -> { final NetworkServer server = new NetworkServer(new InetSocketAddress(3333)); ConcurrentUtils.wait(counter); server.stop(); })).start(); ThreadUtils.sleep(1000); for (int i = 0, length = CLIENT_COUNT; i < length; i++) { new Thread(run(() -> { Socket socket = new Socket(); socket.connect(new InetSocketAddress(3333)); writeLine(socket, "Hello! I'm client " + currentThread().getName()); System.out.println("Client: received: " + readLine(socket)); synchronized (counter) { if (counter.decrementAndGet() == 0) { ConcurrentUtils.notifyAll(counter); } else { ConcurrentUtils.wait(counter); } } socket.close(); })).start(); } Java NIO.2 — Test
  21. 21. Java NIO.2 — Test Server: received: Hello! I'm client Thread-16 Server: received: Hello! I'm client Thread-19 Server: received: Hello! I'm client Thread-11 Server: received: Hello! I'm client Thread-20 Server: received: Hello! I'm client Thread-15 Server: received: Hello! I'm client Thread-18 Server: received: Hello! I'm client Thread-12 Server: received: Hello! I'm client Thread-14 Server: received: Hello! I'm client Thread-13 Server: received: Hello! I'm client Thread-17 Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server! Client: received: Hello! I'm NIO.2 server!
  22. 22. All thanks Repository with my code examples: https://bitbucket.org/JavaSabr/publictest

×