NIO Buffers, Channels, Selectors

NIO Buffers, Channels, Selectors

In the Java programming language, the NIO (New I/O) New Input/Output method was introduced to provide a more efficient and flexible way to handle or manage program input/output data operations compared to the traditional Java I/O method.

NIO Buffers, Channels, Selectors

There are three essential concepts in Java NIO (New I/O).

  • Buffers — These hold data from a Java program in a temporary order.
  • Channels — These provide a connection method for reading/writing data from a Java program.
  • Selectors — These help a single thread in a Java program monitor multiple channels.

Buffers Concept in Java.

A buffer in a Java program is a container value, a container holder, or a method used to hold program data being read or written from a channel.

Common buffer types used in Java.

  • ByteBuffer method.
  • CharBuffer method.
  • The IntBuffer method.
  • The LongBuffer method.
  • The FloatBuffer method.
  • The DoubleBuffer method.
  • The ShortBuffer method.

The most commonly used method in the Java programming language is the ByteBuffer method.

Creating a Buffer in Java.

ByteBuffer buffer = ByteBuffer.allocate(1024);

This creates a new buffer with a capacity of 1024 bytes in the current Java program.

Essential properties of a Java buffer.

A user-created buffer in a Java program mainly has these common elements:

  • Buffer capacity.
  • Buffer position.
  • Buffer limit.

Buffer capacity.

The maximum number of element values ​​or bytes that can be stored in a user-defined custom program buffer.

ByteBuffer buffer = ByteBuffer.allocate(17);

Here in this description.

The buffer’s capacity is defined as 17.

Buffer position.

Indicates the storage location of a user-defined buffer in the current Java program, where data will be read or written.

Buffer limit.

Indicates the limit of a user-defined buffer in the current Java program, up to which data can be read or written.

put() Buffer method in Java.

It is used to create or write buffer data in the current Java program.

ByteBuffer buffer = ByteBuffer.allocate(17);

buffer.put((byte) 17);

buffer.put((byte) 23);

buffer.put((byte) 33);

After writing these statements, the buffer’s position is advanced.

Flip() concept in buffer.

This method prepares the buffer for reading after creating the flip() function in the Java program.

buffer.flip();

According to this concept.

Writing to a Java buffer.

Buffer position → Moves forward.

flip()

↓

Reading the buffer value.

  • Buffer position → Starts the buffer from the beginning.
  • Buffer limit → Sets the amount of data written to it.

get() concept in buffer.

In Java programs, the get() function method is used to read data information from a buffer.

byte data = buffer.get();

System.out.println(data);

clear() concept in buffer.

In Java programs, the clear() function method prepares a buffer for writing new data.

buffer.clear();

The clear() function resets the position and limit for the next write cycle.

Example of the buffer method in Java.

ByteBuffer buffer =

import java.nio.ByteBuffer;

public class ByteBufferTesting {

public static void main(String[] args) {

// here we Allocate a ByteBuffer with capacity 17 bytes in java program

ByteBuffer buffer = ByteBuffer.allocate(17);

// here we put new values ​​into the buffer

buffer.put((byte) 17);

buffer.put((byte) 23);

buffer.put((byte) 33);

buffer.put((byte) 43);

// here we use Flip the buffer to switch from writing mode to reading mode

buffer.flip();

// here we Read and print values ​​from the buffer element

System.out.println(“The Buffer elements is -:”);

while (buffer.hasRemaining()) {

System.out.println(buffer.get());

}

}

}

Its output.

The Buffer elements are-:

17

23

33

43

Common Java Used Popular Buffer Methods

#Buffer MethodsPurpose of Each Buffer Methods
1.allocate() functionallocate() function used to Creates a buffer element
2.put()functionput()function used to Writes buffer data
3.get()functionget()function used to Reads data or buffer element
4.flip()functionflip()function used to Switches writing mode to reading mode file data
5.clear()functionclear()function used to Prepares buffer for new writing element
6.rewind()functionrewind()function method used to Moves position back to beginning
7.hasRemaining()functionhasRemaining()function used to Checks whether data remains or not

Channel Concept in Java.

In a Java buffer program, a channel represents a connection; data can be read or written through a channel connection.

Unlike traditional stream methods in Java, channels can support both read and write operations, depending on the channel type.

Common channels in Java include.

  • FileChannel
  • SocketChannel
  • ServerSocketChannel
  • DatagramChannel
  • FileChannel Concept in Java.

The FileChannel method concept is used in Java programs to read and write Java data files.

Example of the FileChannel Concept.

FileChannel channel =

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

public class FileChannelIllustration {

public static void main(String[] args) {

try {

// here we Open the file in READ mode data operation

FileChannel channel = FileChannel.open(

Paths.get(“samplefile.txt”),

StandardOpenOption.READ

);

// here we Allocate a ByteBuffer of 1024 bytes disk space allocation

ByteBuffer buffer = ByteBuffer.allocate(1024);

// here we Read file data into the buffer mode

channel.read(buffer);

// here we Switch buffer from writing mode to reading mode task

buffer.flip();

// here we Read and display file contents elements

while (buffer.hasRemaining()) {

System.out.print((char)buffer.get());

}

// here we close the channel

channel.close();

} catch (IOException ex) {

System.out.println(“Display Error while reading file data -: ” + ex.getMessage());

}

}

}

A basic Java channel flow concept.

data file

↓

FileChannel Method

↓

bytebuffer storage element

↓

application

Writing using a FileChannel in Java.

FileChannel channel =

String text = “Welcome to Java NIO features”;

ByteBuffer buffer =

ByteBuffer.wrap(text.getBytes());

Example of Writing using a FileChannel in Java.

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

public class FileChannelWriteIllustration {

public static void main(String[] args) {

try {

// here we create data to write into the file

String info = “Welcome to Java NIO features. \nWelcome to FileChannel concept.”;

// here we Convert string into bytes and store in ByteBuffer method

ByteBuffer buffer = ByteBuffer.wrap(info.getBytes());

// here we Open file in CREATE and WRITE mode file operation

FileChannel channel = FileChannel.open(

Paths.get(“samplefile.txt”),

StandardOpenOption.CREATE,

StandardOpenOption.WRITE

);

//here we Write buffer data into the file

while (buffer.hasRemaining()) {

channel.write(buffer);

}

//here we close the channel

channel.close();

System.out.println(“Sample file Data written successfully”);

} catch (IOException ex) {

System.out.println(“Display Error writing into the file -: ” + ex.getMessage());

}

}

}

Socket channel concept in Java.

The socket channel in Java also provides a channel for NIO network communication.

ServerSocketChannel.

The ServerSocketChannel method is used to create a server socket channel in Java.

ServerSocketChannel server =

ServerSocketChannel.open();

server.bind(

new InetSocketAddress(8080)

);

SocketChannel.

The SocketChannel method is used for communication between a client and a server in Java programs.

SocketChannel client =

SocketChannel.open(

new InetSocketAddress(“localhost”, 8080)

);

Channels in Java can operate in either blocking or non-blocking mode.

For example.

server.configureBlocking(false);

These are useful in Java programs with a non-blocking channel selector in a specific order.

Selector Methods in Java.

A selector in a Java program helps a single thread monitor multiple channels.

This is especially useful for network applications. Without a selector method:

  • Program thread 1 → Channel 1 method
  • Program thread 2 → Channel 2 method
  • Program thread 3 → Channel 3 method
  • Program thread 4 → Channel 4 method

Channel method with a selector.

┌→ Channel 1 method

│

Single program thread → Selector

│

├→ Channel 2 method

│

└→ Channel 3 method

Here we can reduce the need for one thread for each connection.

Creating a selector in Java.

Selector selector =

selector.open(); function.

In this thread, the channel must be configured as non-blocking before registering it with the selector.

channel.configureBlocking(false);

Then register it.

channel.register(

selector,

SelectionKey.OP_READ

);

Selector Selection Operations in java.

Some of the most popular selection operations used in the Java programming language are:

#Selector OperationMeaning of Selector Operations
1.OP_READ operationOP_READ operation used to check outchannel is ready for reading or not
2.OP_WRITE operationOP_WRITE operation used to check out channel is ready for writing
3.OP_CONNECT operationOP_CONNECT operation used to check out connection can be established or not
4.OP_ACCEPT operationOP_ACCEPT operation used to check out the server can accept a connection or not

Example of a selection operation.

channel.register(

selector,

SelectionKey.OP_READ

);

Using Selector Methods in Java.

In the Java programming language, a typical selector loop is represented by:

while (true) {

selector.select();

Set<SelectionKey> keys =

selector.selectedKeys();

for (SelectionKey key : keys) {

if (key.isReadable()) {

// Here it reads data

}

if (key.isWritable()) {

// Here it writes data

}

}

keys.clear();

}

In this process, the selector waits until one or more registered channels are ready for operation.

Relationship between buffer, channel, and selector in Java.

These three concepts work together in a basic Java program.

Selector Method

↓

The channel it monitors

↓

Channel Concept

↓

Reads and writes data to

↓

Buffer Memory

↓

Final Application

For example, in a network application.

Client Request

↓

SocketChannel Method

↓

Selector Process

↓

Readable?

↓

ByteBuffer

↓

Process Data Element

Difference Between Buffer, Channel, and Selector.

#Each FeatureBuffer methodChannel methodSelector method
1.Unique purposeIt Holds data or value elementIt Transfers data elementIt Monitors all channels
2.What Used forIt provides Temporary storage holdProvide readymade I/O communication methodIt provides Multiplexing concept
3.Example withUsed with ByteBuffer methodUsed with FileChannel methodUsed with Selector method
4.Implement withBuffer implement with DataChanel implements with Files/networkSelector implement with Multiple channels
5.Popular methodsPopular buffer method or function put(), get(), flip()Popular channel method or function read(), write()Popular selector method or function select(), selectedKeys()

Conclusion of NIO Buffers, Channels, Selectors.

Easy Way to Remember

  • Buffer Method → ​​Where is the data to be processed stored in the buffer.
  • Channel Method → ​​How is data moved from source to destination in a buffer channel.
  • Selector Method → ​​Which channel is ready for buffer operation.

In short, NIO programs in Java use the selector method to efficiently monitor channels for I/O, buffers to hold data during I/O input/output operations, and multiple non-blocking channels with fewer threads.

Leave a Reply