首頁  >  文章  >  Java  >  Java NIO中的非阻塞伺服器

Java NIO中的非阻塞伺服器

王林
王林轉載
2023-08-19 18:49:071276瀏覽

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 JDKuction since JDKly s intophisticated features since JDK 4's intthemhas sgemhas sgemhased since JDKly since int quem) 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 proces 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 howhow# pipe worksdown of how找到 works worksdown of works −p

  • 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 streamces #eforef

  • 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 quest to reefore wait for request A to be fully processed before quest to reefore quest B. 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 wection data .over

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, andchan's fundamental chanoo selectors make it a unique I/O system.

Java NIO的非阻塞伺服器模型能夠透過使用非阻塞I/O管道同時處理多個請求。與阻塞I/O管道不同,非阻塞模型只檢查並提供那些實際上有資料可讀的SelectableChannel實例,使其成為更快、更有效率的系統。

以上是Java NIO中的非阻塞伺服器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除