0

0

Java NIO中的非阻塞服务器

王林

王林

发布时间:2023-08-19 18:49:07

|

1371人浏览过

|

来源于tutorialspoint

转载

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,非阻塞服务器可以通过同一进程或线程同时处理多个请求。将阻塞进程视为售票处的队列,每个顾客必须等待前面的人被服务完才能继续。

立即学习Java免费学习笔记(深入)”;

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 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 −

Android数据格式解析对象JSON用法 WORD版
Android数据格式解析对象JSON用法 WORD版

本文档主要讲述的是Android数据格式解析对象JSON用法;JSON可以将Java对象转成json格式的字符串,可以将json字符串转换成Java。比XML更轻量级,Json使用起来比较轻便和简单。JSON数据格式,在Android中被广泛运用于客户端和服务器通信,在网络数据传输与解析时非常方便。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看

下载
  • 缓冲区− 缓冲区是一块用于临时存储数据的内存块,用于在数据从一个位置传输到另一个位置时使用。在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速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
C++ 高级模板编程与元编程
C++ 高级模板编程与元编程

本专题深入讲解 C++ 中的高级模板编程与元编程技术,涵盖模板特化、SFINAE、模板递归、类型萃取、编译时常量与计算、C++17 的折叠表达式与变长模板参数等。通过多个实际示例,帮助开发者掌握 如何利用 C++ 模板机制编写高效、可扩展的通用代码,并提升代码的灵活性与性能。

6

2026.01.23

php远程文件教程合集
php远程文件教程合集

本专题整合了php远程文件相关教程,阅读专题下面的文章了解更多详细内容。

21

2026.01.22

PHP后端开发相关内容汇总
PHP后端开发相关内容汇总

本专题整合了PHP后端开发相关内容,阅读专题下面的文章了解更多详细内容。

16

2026.01.22

php会话教程合集
php会话教程合集

本专题整合了php会话教程相关合集,阅读专题下面的文章了解更多详细内容。

11

2026.01.22

宝塔PHP8.4相关教程汇总
宝塔PHP8.4相关教程汇总

本专题整合了宝塔PHP8.4相关教程,阅读专题下面的文章了解更多详细内容。

9

2026.01.22

PHP特殊符号教程合集
PHP特殊符号教程合集

本专题整合了PHP特殊符号相关处理方法,阅读专题下面的文章了解更多详细内容。

9

2026.01.22

PHP探针相关教程合集
PHP探针相关教程合集

本专题整合了PHP探针相关教程,阅读专题下面的文章了解更多详细内容。

7

2026.01.22

菜鸟裹裹入口以及教程汇总
菜鸟裹裹入口以及教程汇总

本专题整合了菜鸟裹裹入口地址及教程分享,阅读专题下面的文章了解更多详细内容。

24

2026.01.22

Golang 性能分析与pprof调优实战
Golang 性能分析与pprof调优实战

本专题系统讲解 Golang 应用的性能分析与调优方法,重点覆盖 pprof 的使用方式,包括 CPU、内存、阻塞与 goroutine 分析,火焰图解读,常见性能瓶颈定位思路,以及在真实项目中进行针对性优化的实践技巧。通过案例讲解,帮助开发者掌握 用数据驱动的方式持续提升 Go 程序性能与稳定性。

9

2026.01.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号