Your SlideShare is downloading. ×
NIO and NIO2
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

NIO and NIO2


Published on

Whats new in NIO and NIO2

Whats new in NIO and NIO2

Published in: Technology, Education

1 Comment
No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. What's New in NIO 2
    Ranjith Kumar N
    9th June 2011
  • 2. Agenda:
    NIO 2.0
    • Update
    • 5. New File System API
    • 6. Asynchronous I/O
  • Why NIO?
    JSR - 51
  • 7. NIO Features
    Channel and Buffers
    File locking
    Memory Mapped Files
    Scatter and Gather
    Channel to Channel Transfer
    Non-Blocking Sockets
    Multiplexed I/O
  • 8. Buffersjava.nio
  • 9. Buffer's Basic Attributes:
  • 10. Buffer Basic Operations:
    Filling and Draining
    Flipping and Rewind
  • 11. Creating
    public static XXXBuffer allocate (int capacity)
    public static XXXBuffer wrap (XXX [] array)
    public static XXXBuffer wrap (XXX [] array, int offset,int length)
    For e.g.
    CharBuffer charBuffer= CharBuffer.allocate(10);
    char [] charArray = new char [10];
    CharBuffercharbuffer = CharBuffer.wrap (charArray );
    CharBuffercharbuffer = CharBuffer.wrap (charArray, 2, 7);
  • 12. Filling and Draining
    XXXBuffer put (XXX b);
    XXXBuffer put (int index, XXX b);
    XXX get( );
    XXX get(int index);
    XXXBufferput (XXX[] src);
    XXXBuffer put(XXX [] src, int offset, int length);
    XXXBuffer get(XXX[] dest);
    XXXBuffer get(XXX [] dest, int offset, int length);
  • 13. Flipping and Rewind
    Manually Flipping a Buffer:
    buffer.limit(buffer.position( )).position(0)
    API provides Flip and rewind method:
    Buffer flip()
    Buffer rewind()
  • 14. Marking
    Buffer mark()
    Buffer reset()
    For e.g
    buffer.position(2).mark( ).position(4);
  • 15. Marking - cont.
    After calling reset method
  • 16. Comparing
    boolean equals (Object ob)
    int compareTo (Object ob)
    Two buffers are considered to be equal if and only if:
    • Both objects are the same type
    • 17. Both buffers have the same number of remaining elements.
    • 18. The sequence of remaining data elements, which would be returned from get( ), must be identical in each buffer.
  • Comparing – cont.
    Two buffers considered to be equal
  • 19. Comparing – cont.
    Two buffers considered to be unequal
  • 20. Duplicating
    CharBuffer duplicate( );
    CharBuffer asReadOnlyBuffer( );
    CharBuffer slice( );
    For e.g
    CharBuffer buffer = CharBuffer.allocate (8);
    buffer.position(3).limit (6).mark( ).position (5);
    CharBuffer dupeBuffer = buffer.duplicate( );
    buffer.clear( );
  • 21. Duplicating – cont.
  • 22. Duplicating – cont.
    CharBuffer buffer = CharBuffer.allocate (8);
    buffer.position(3).limit (5);
    CharBuffer sliceBuffer = buffer.slice( );
  • 23. Byte Buffers
  • 24. Direct Buffers:
    ByteBuffer allocateDirect (int capacity)
    boolean isDirect( );
    If Direct Buffers are not used
    • Create a temporary Direct ByteBuffer object.
    • 25. Copy the content of the nondirect buffer to the temporary buffer.
    • 26. Perform the low-level I/O operation using the temporary buffer.
    • 27. The temporary buffer object goes out of scope and is eventually garbage collected.
  • Duplicating:
    CharBuffer asCharBuffer( );
    ShortBuffer asShortBuffer( );
    IntBuffer asIntBuffer( );
    LongBuffer asLongBuffer( );
    FloatBuffer asFloatBuffer( );
    DoubleBuffer asDoubleBuffer( );
  • 28. View Buffers: cont.
    ByteBuffer byteBuffer =ByteBuffer.allocate (7);
    CharBuffer charBuffer = byteBuffer.asCharBuffer( );
  • 29. Channeljava.nio.channels
  • 30. Channel basics
  • 31. Creating
    SocketChannel sc = );
    ServerSocketChannelssc = );
    DatagramChannel dc = );
    RandomAccessFileraf = new RandomAccessFile ("somefile", "r");
    FileChannel fc = raf.getChannel( );
  • 32. Reading/Writing
    • read (ByteBuffer dst)
    • write (ByteBuffer src)
    FileInputStream input = new FileInputStream(fileName);
    FileChannel channel = input.getChannel( );;
  • 33. Scatter/Gather
    read (ByteBuffer [] dsts)
    read (ByteBuffer [] dsts, int offset, int length)
    write(ByteBuffer[] srcs)
    write(ByteBuffer[] srcs, int offset, int length)
  • 34. Closing
    • boolean isOpen( );
    • 35. void close( )
  • FileChanneljava.nio.channels
  • 36. File Locking
    FileLock lock( )
    FileLock lock (long position, long size,boolean shared)
    FileLocktryLock( )
    FileLocktryLock (long position, long size,boolean shared)
  • 37. Memory-Mapped Files
    MappedByteBuffer map (MapMode mode, long position,long size)
  • 38. Channel 2 Channel transfer
    transferTo (long position, long count, WritableByteChannel target)
    transferFrom (ReadableByteChannel src,long position, long count)
  • 39. Socket Channelsjava.nio.channels
  • 40. Non-blocking Mode
    configureBlocking (boolean block)
    boolean isBlocking( )
    Object blockingLock( )
    SocketChannel sc = );
    sc.configureBlocking (false); // nonblocking mode
    sc.configureBlocking (true); // blocking mode
  • 41. Readiness Selection
    Socket channels can be check for readiness
    A single thread can monitor a large number of socket
    Steps to do readiness selection
    Create a Selector instance
    Register one or more non-blocking channels with it
    Implement a infinite loop and wait for events
    Get the selected keys list and iterate the keys
    Process the events.
    Remove the key from the list
  • 42. Readiness Selection
    Selector selector =;
    ServerSocketChannelserverChannel =;
    serverChannel.socket().bind (new InetSocketAddress (port));
    serverChannel.configureBlocking (false);
    SelectionKeyregisteredkey = serverChannel.register (selector, SelectionKey.OP_ACCEPT);
    while (true) {;
    Iterator it = selector.selectedKeys().iterator();
    while (it.hasNext()) {
    SelectionKey key = (SelectionKey);
  • 43. Selector
    Key Methods:
    Selector open( )
    int select( )
    int select (long timeout)
    int selectNow( )
    Set keys( )
    Set selectedKeys( )
  • 44. SelectableChannel
    Key methods:
    SelectionKey register (Selector sel, int ops)
    booleanisRegistered( );
    SelectionKeykeyFor (Selector sel);
    int validOps( );
  • 45. SelectionKey
    Key methods:
    SelectableChannel channel( )
    Selector selector( )
    void cancel( )
    boolean isValid( )
    booleanisReadable( )
    boolean isWritable( )
    boolean isConnectable( )
    boolean isAcceptable( )
    Operations to select:
    int OP_READ
    int OP_WRITE
    int OP_CONNECT
    int OP_ACCEPT
  • 46. NIO 2JSR-203
  • 47. FileChanneljava.nio.channels
    FileChannel open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)
     FileChannel open(Path path, OpenOption... options)
    Path file= Paths.get("C:homejugcread.txt");
    FileChannelfc = (, WRITE, APPEND ));
  • 48. StandardOpenOption Enumjava.nio.file
  • 49. SeekableByteChannel
    A byte channel that maintains a current position and allows the position to be changed.
    Key Methods
    SeekableByteChannel position(long newPosition)
    SeekableByteChannel truncate(long size)
  • 50. NetworkChannel & MulticastChanneljava.nio.channels
    All the network-oriented channels implements the new NetworkChannel interface
    We can easily bind the channel socket, set and query for socket options
    We can send and receive IP datagrams from a complete group
    Implement by DatagramChannel and AsynchronousDatagramChannel
  • 51. Pathjava.nio.file
    Locates a file using a system dependent path
    Defines methods to access and manipulate paths
    Defines methods to access files
  • 52. Creating a Path
    // Microsoft Windows
    Path p1 = Paths.get("C:homejoefoo");
    // Solaris syntax
    Path path = Paths.get("/home/joe/foo");
    Path p4 = FileSystems.getDefault().getPath("/users/sally");
  • 53. Key Methods
    Path normalize()
    Path toAbsolutePath()
    Path toRealPath(LinkOption... options)
    Path resolve(Path other)
    Path relativize(Path other)
  • 54. Files java.nio.file
    Helper Class
    Create file, directory and links
  • 55. Copy
    long copy(InputStream in, Path target, CopyOption... options)
    long copy(Path source, OutputStream out)
    Path copy(Path source, Path target, CopyOption... options)
  • 56. Move & Delete
    void delete(Path path)
    booleandeleteIfExists(Path path)
    Path move(Path source, Path target, CopyOption... options)
  • 57. File, Directory and link
    Path createFile(Path path, FileAttribute<?>... attrs)
    Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs)
    Path createDirectory(Path dir, FileAttribute<?>... attrs)
    Path createDirectories(Path dir, FileAttribute<?>... attrs)
    Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs)
    Path createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs)
  • 58. Walk File Tree
    Walk a file tree rooted at a given starting file
    Implement FileVisitor interface
    Initiate the process by calling anyone of the below method of java.nio.file.FilesClass
    walkFileTree(Path start, FileVisitor<? super Path> visitor)
    walkFileTree(Path start, Set<FileVisitOption> options, intmaxDepth, FileVisitor<? super Path> visitor)
  • 59. FileVisitorjava.nio.file
    FileVisitResultpreVisitDirectory(T dir);
    FileVisitResultvisitFile(T file, BasicFileAttributes attrs);
    FileVisitResultpostVisitDirectory(T dir, IOExceptionexc);
    FileVisitResultpreVisitDirectoryFailed(T dir, IOExceptionexc);
    FileVisitResultvisitFileFailed(T file, IOExceptionexc);
  • 60. FileVisitor Callback Methods
    Previsit Directory
    File 1
    Root 1
    Previsit Directory
    File 2
    File 3
  • 61. File Change Notification
    Looking for file changes in FileSystem
    Using the native event facility whenever available
    Steps required to implement a watch service
    Create a WatchService "watcher" for the file system.
    For each directory that you want monitored, register it with the watcher.
    Implement an infinite loop to wait for incoming events
    Retrieve the key from the watcher's queue.
    Process all the events associated with the Key.
    Reset the key, and resume waiting for events.
    Close the service
  • 62. File Change Notification – cont.
    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path dir= Paths.get("C:homewatchdir");
    WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    for( ; ; ){
    WatchKeysignalledkey = watcher.take();
    for (WatchEvent<?> event: signalledkey .pollEvents()) {
    WatchEvent.Kind<?> kind = event.kind();
    // process the event
    boolean valid = signalledkey .reset();
    if (!valid) {
  • 63. WatchServicejava.nio.file
    Watch registered objects for events and changes
    Key Methods
    WatchKey poll()
    WatchKey poll(long timeout, TimeUnit unit)
    WatchKey take()
    void close()
  • 64. WatchKeyjava.nio.file
    WatchKey represents registration of a watchable
    object with a WatchService.
    Key Methods:
    List<WatchEvent<?>> pollEvents()
    Watchable watchable()
    boolean reset()
    boolean isValid()
    void cancel()
  • 65. File Attributesjava.nio.file.attribute
    Meta-data associated with file
    Generalized metadata API
    Fetch a file's attributes in one bulk operation
    Map<String,Object> readAttributes(Path, String, LinkOption...)
    <A extends BasicFileAttributes> readAttributes(Path, Class<A>, LinkOption...)
    Grouping of related attributes and Views to access the attribute groups.
  • 66. Attributes View
    File Attributesjava.nio.file.attribute
  • 67. File Attributesjava.nio.file.attribute
    Path file = Paths.get("C:homefile.txt"); ;
    BasicFileAttributesattr = Files.readAttributes(file, BasicFileAttributes.class);
    DosFileAttributesdosattr = Files.readAttributes(file, DosFileAttributes.class);
    PosixFileAttributesposixattr = Files.readAttributes(file, PosixFileAttributes.class);
  • 68. Asynchronous I/Ojava.nio.channels
    They provide asynchronous operations for both sockets and files.
    All operations work in non-blocking mode.
    All the asynchronous I/O operations have one of two forms :
    The first one returns a java.util.concurrent.Future that represent the pending result
    The second one is created using a CompletionHandler.
  • 69. Futurejava.util.concurrent
    AsynchronousFileChannel channel =“C:homeasyncfile.txt "));
    ByteBuffer buffer = ByteBuffer.allocate(100);
    Future result =, 100);
    boolean done = result.isDone();
  • 70. CompletionHandler
    Future result =, 100, buffer, new CompletionHandler(){
    public void completed(Integer result, ByteBuffer buffer){
    //Compute the result
    public void failed(Throwable exception, ByteBuffer buffer){
    // Handle the error
  • 71. References:
    Java NIO by Ron Hitchens Publisher: O’Reilly
  • 72. Thanks U!!!!