Java NIO: Selector

Taking FileChannel for example in the previous post may bewilder audiences: it’s non-blocking, so how does NIO achievement non-blocking? Here comes Selector. A Selector is a Java NIO component which can examine one or more NIO Channel’s, and determine which channels are ready for reading or writing. A thread can manage multiply channels with Selector making multiple network connections feasible. This way avoids the cost of switching between threads which is expensive. Here is an illustration of a thread using a Selector to handle 3 Channels: ...

Jul 21, 2018 · 9 min · xgugeng

Java NIO: Channel

Channels are similar to streams available for blocking IO with a few differences: You can both read and write to Channels. Streams are typically one-way (read or write). Channels can be read and written asynchronously. Channels always read to, or write from, a Buffer. The Channels have multiple implementations depending on the data to be read or written: FileChannel: Used to read and write data from and to the files DatagramChannel: Used for data exchange over network using UDP packets SocketChannel: TCP channel to exchange data over TCP sockets ServerSocketChannel: An implementation similar to a web server listening to requests over a specific TCP port. It creates a new SocketChannel instance for every new connection This post will take FileChannel for further exploration, from example to implementation. ...

Jul 19, 2018 · 7 min · xgugeng

Java NIO: Buffer

Java NIO (New IO), introduced by Java 1.4, is an alternative IO API for Java. It offers a different way of working with IO than the standard IO API’s. Three core components of Java NIO cover: Channels Buffers Selectors All IO in NIO involves with Channel. Data can be read from Channel to a Buffer and vice versa. Buffers are used to interact with Channels. A Buffer is an allocated block of memory with fixed size, into which you can read or write data. In this post, I’ll illustrate the basic usage of Buffer and elucidate how it manages to do that from the view of source code. ...

Jul 14, 2018 · 7 min · xgugeng