讲师中心 微信公众号
AI工具推荐 视频效率加速

Java NIO中的非阻塞服务器

陌敏吖_2360

陌敏吖_2360

发布时间: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<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速学教程(入门到精通)
java速学教程(入门到精通)

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

下载

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

热门AI工具

更多
Laper
Laper Hot

Laper是专为编剧、导演和制片人推出的 AI 原生剧本创作工具。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

音述AI
音述AI Hot

一款AI音频处理工具,主要用于音述AI是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区,适合需要提升相关任务效率的用户。

Lovart
Lovart Hot

一款面向视觉设计创作的AI设计平台,可通过智能体和画布工作流辅助制作海报、Logo、网页、PPT及其他视觉内容。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

二狗PPT
二狗PPT Hot

一款AI演示文稿工具,主要用于专为中式职场打造的AI PPT生成工具,适合需要提升相关任务效率的用户。

切问学术

切问学术是一款AI论文写作工具,复旦大学NLP团队推出的AI学术智能体。

咔片AIPPT

一款在线AI演示文稿制作工具,可根据主题和内容需求辅助生成PPT结构与页面,提高演示材料制作效率。

相关专题

更多
Buffalo框架数据库开发全教程
Buffalo框架数据库开发全教程

本专题围绕Buffalo框架数据库开发,讲解database.yml多环境配置、soda与fizz迁移生成回滚、模型结构体标签、增删改查与条件查询、一对多与多对多关联、数据校验、回调钩子、事务处理及原生SQL执行能力。

20

2026.09.23

Buffalo框架路由与请求处理实操指南
Buffalo框架路由与请求处理实操指南

本专题讲解Buffalo框架路由与请求处理机制,涵盖路由注册与分组、资源路由、Handler编写规范、Context上下文方法、参数绑定、中间件编写挂载、Session与Cookie读写、Flash消息及错误页面定制方法。

0

2026.09.23

Buffalo框架零基础入门教程
Buffalo框架零基础入门教程

本专题整理Buffalo框架入门内容,涵盖Go环境准备、buffalo CLI安装、新项目生成、目录结构说明、dev热加载启动、数据库连接配置与常见报错排查,帮助新手按约定优于配置的思路跑通第一个Buffalo框架应用。

20

2026.09.23

Conan创建软件包配方指南
Conan创建软件包配方指南

本专题介绍通过conanfile.py创建软件包的方法,讲解包名、版本、依赖和构建设置等基础信息,以及source、build、package、package_info等常用方法的作用及编写思路。

0

2026.09.22

Conan二进制包配置指南
Conan二进制包配置指南

本专题介绍Conan根据操作系统、编译器、架构和构建类型生成二进制包的方法,讲解Profile、Settings、Options及Package ID的作用,帮助管理不同平台和编译环境下的包版本。

20

2026.09.22

Conan私有仓库搭建教程
Conan私有仓库搭建教程

本专题系统的讲解Conan私有仓库的搭建流程,涵盖仓库服务部署、存储目录配置、用户认证、权限划分和远程地址添加,并介绍内部C++依赖包的上传、下载及版本维护方法。

20

2026.09.22

loomy官网入口地址合集
loomy官网入口地址合集

本专题汇总了 Loomy 桌面 AI 助理的官方入口地址合集及使用指南。提供 macOS 与 Windows 客户端下载 。Loomy 是讯飞推出的桌面级 AI 工作搭子,支持文件整理、数据分析、网页操作及通过飞书/钉钉远程操控电脑,助你高效完成本地办公任务 。

20

2026.09.22

NumPy常见函数使用方法
NumPy常见函数使用方法

本专题整理 NumPy 常见函数使用方法相关教程,覆盖函数大全、参数用法、数组运算、统计聚合、排序处理、where 条件筛选、linspace 创建数列等常用场景,帮助读者快速掌握 NumPy 函数调用思路和实际数据处理技巧。

0

2026.09.22

NumPy性能优化版本更新与常见报错排查
NumPy性能优化版本更新与常见报错排查

本专题整理 NumPy 性能优化、版本更新与常见报错排查相关教程,覆盖向量化计算、广播性能、内存布局、NumPy 2.0 升级、版本兼容冲突、安装导入报错、dtype 溢出、矩阵运算异常和 broadcasting 报错修复,帮助读者系统掌握 NumPy 性能调优与问题定位方法。

20

2026.09.22

热门下载

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

精品课程

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

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn