首页 >Java >java教程 >Java NIO中的非阻塞服务器

Java NIO中的非阻塞服务器

王林
王林转载
2023-08-19 18:49:071336浏览

Java NIO中的非阻塞服务器

Non-blocking Server

Java NIO (New Input/Output) is a very powerful networking and file-handling application that functions as an alternative to Java's standard IO API. Due to the addition of more sophisticated features since JDK 4's introduction, it has quickly emerged as the preferred I/O system among numerous engineers.

Java NIO提供的对文件处理和文件系统功能的改进支持是其区别于其他特性之一。由于NIO文件类具有如此强大的功能,因此在文件处理中被广泛使用。

如果你仔细观察,你会注意到java.nio包指定了NIO API中使用的缓冲区类。最好的一点是,它是为了让Java程序员能够在不编写本地代码的情况下实现快速I/O而创建的。

阻塞与非阻塞I/O

由于其使用了非阻塞I/O,非阻塞服务器可以通过同一进程或线程同时处理多个请求。将阻塞进程视为售票处的队列,每个顾客必须等待前面的人被服务完才能继续。

In contrast, a non-blocking process is like a waiter at a restaurant who tries to serve all customers simultaneously by rotating through them and taking care of their orders.

阻塞服务器以同步方式工作,完成每个请求后再转到下一个。这可能导致客户端等待时间较长,并且需要多个线程来处理每个请求,使其对CPU要求较高。另一方面,非阻塞服务器采用异步方法,允许一个线程在同一时间处理多个查询,对每个请求的完成做出反应。

Java NIO的特点

Java NIO 有一些独特的特点,使其与其他 IO 系统区别开来。以下是 Java NIO 的主要特点:

  • Asynchronous and Non-Blocking IO − This feature allows for threads to perform other tasks while data is being read into a buffer. Instead of waiting for data to be fully loaded before processing begins, threads can continue their work while the data is being read.

  • 缓冲区导向的方法 − Java NIO将数据存储在缓冲区中,这样可以快速访问和处理。当需要数据时,它会从缓冲区中检索和处理。

算法

  • Step 1 − To begin with, we must import the necessary classes using the import statement.

  • Step 2 − Next, we need to create a public class named "WriteExample2."

  • Step 3 − Inside this class, we must define a public static void main function that accepts String-type variable arguments.

  • Step 4 − Now, create a temporary file with the ".txt" extension by using the Files.createTempFile() method. To write, we can use the Files.write() method along with an iterable object holding the strings "Hello" and "world."

  • Step 5 − To read every byte from the file defined by the Path object returned by the Files' createTempFile() function, we can use the Files.readAllBytes() function. After that, we need to convert them to a String using the new String() constructor.

  • Step 6 − Lastly, print the String to the console using the System.out.println() method.

Example 1

This Java code creates a temporary text file and writes "Hello" and "world" to it. It then reads the file and prints its contents. The code uses the Files class from the Java NIO package to handle file operations.

package com.tutorialspoint.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;

public class WriteExample2 {
   public static void main(String... args) throws IOException {
      Path path = Files.createTempFile("test-file", ".txt");
      Iterable<String> iterable = Arrays.asList("Hello", "world");
      Files.write(path, iterable);
      byte[] bytes = Files.readAllBytes(path);
      System.out.println(new String(bytes));
   }
}

输出

Hello
world

Components of Java NIO

Java NIO is built on three fundamental components: Buffers, Channels, and Selectors. Here's a brief overview of each −

  • 缓冲区− 缓冲区是一块用于临时存储数据的内存块,用于在数据从一个位置传输到另一个位置时使用。在Java NIO中,缓冲区用于方便地读取和写入数据。

  • 通道 - 在Java NIO中,通道代表与可以执行IO操作的对象(如文件和套接字)的连接。通道负责在缓冲区和它们所代表的对象之间传输数据。

  • Selectors − A selector is a Java NIO component used to monitor one or more channels for events, such as readiness to perform an I/O operation. When a channel is ready, the selector can wake up and allow the appropriate thread to handle the operation.

Non-Blocking Server Composition

Non-blocking servers are composed of a non-blocking IO pipeline, which is a chain of components that process both read and write IO operations in a non-blocking fashion. Here's a breakdown of how this pipeline works −

  • A selector is used by each component in the pipeline to determine whether a channel has data to read.

  • When there is data, the component reads it and provides output based on it. After that, the output is written back to the channel.

  • 基于组件,非阻塞IO管道可以读取和写入数据,以及执行这两种操作。

  • 该组件通过选择器从通道中读取数据。Java NIO管理非阻塞IO操作,而选择器和可选择通道的选择键定义了多路复用的IO操作。

  • Non-blocking IO pipelines divide data into logically ordered or combined messages alongside non-blocking data processing. This is comparable to using Java's StreamTokenizer class to tokenize a stream of data before processing it.

  • Non-blocking models employ Java NIO selectors to check and give only those SelectableChannel instances that have data to read, as opposed to blocking IO pipelines, which use an interface similar to InputStream and only allow one byte to be read at a time.

Comparison of Blocking and Non-Blocking Models for Server Read/Write Operations

在服务器架构的世界中,选择使用阻塞或非阻塞模型来进行读写操作,可以极大地影响服务器的效率和可扩展性。

非阻塞模型与阻塞模型相反,它允许一个进程通过交错非阻塞I/O调用来处理多个并发请求。

To illustrate the difference between these models, let's consider a hypothetical server that receives two requests. In a blocking model, the process must wait for request A to be fully processed before moving on to request B. In contrast, a non-blocking model can handle both requests simultaneously by interleaving the processing of requests A and B.

Java NIO使得单个线程能够控制多个通道,支持非阻塞I/O。

The channels that link a buffer and an object at the other end make asynchronous data transfer possible. Two classes, SocketChannel and ServerSocketChannel, implement the Java NIO channel and make it possible to receive and write data over TCP connections.

Server architects can create systems that are effective, scalable, and can manage numerous simultaneous requests by selecting the proper I/O model.

结论

Java NIO provides a powerful networking and file-handling application with improved support for file handling and file system features. Its asynchronous and non-blocking I/O, buffer-oriented approach, and three fundamental components of buffers, channels, and selectors make it a unique I/O system.

Java NIO的非阻塞服务器模型能够通过使用非阻塞I/O管道同时处理多个请求。与阻塞I/O管道不同,非阻塞模型只检查和提供那些实际上有数据可读的SelectableChannel实例,使其成为一个更快、更高效的系统。

以上是Java NIO中的非阻塞服务器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除