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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
拼多多赚钱的5种方法 拼多多赚钱的5种方法
拼多多赚钱的5种方法 拼多多赚钱的5种方法

在拼多多上赚钱主要可以通过无货源模式一件代发、精细化运营特色店铺、参与官方高流量活动、利用拼团机制社交裂变,以及成为多多进宝推广员这5种方法实现。核心策略在于通过低成本、高效率的供应链管理与营销,利用平台社交电商红利实现盈利。

4

2026.01.26

edge浏览器怎样设置主页 edge浏览器自定义设置教程
edge浏览器怎样设置主页 edge浏览器自定义设置教程

在Edge浏览器中设置主页,请依次点击右上角“...”图标 > 设置 > 开始、主页和新建标签页。在“Microsoft Edge 启动时”选择“打开以下页面”,点击“添加新页面”并输入网址。若要使用主页按钮,需在“外观”设置中开启“显示主页按钮”并设定网址。

6

2026.01.26

苹果官方查询网站 苹果手机正品激活查询入口
苹果官方查询网站 苹果手机正品激活查询入口

苹果官方查询网站主要通过 checkcoverage.apple.com/cn/zh/ 进行,可用于查询序列号(SN)对应的保修状态、激活日期及技术支持服务。此外,查找丢失设备请使用 iCloud.com/find,购买信息与物流可访问 Apple (中国大陆) 订单状态页面。

16

2026.01.26

npd人格什么意思 npd人格有什么特征
npd人格什么意思 npd人格有什么特征

NPD(Narcissistic Personality Disorder)即自恋型人格障碍,是一种心理健康问题,特点是极度夸大自我重要性、需要过度赞美与关注,同时极度缺乏共情能力,背后常掩藏着低自尊和不安全感,影响人际关系、工作和生活,通常在青少年时期开始显现,需由专业人士诊断。

3

2026.01.26

windows安全中心怎么关闭 windows安全中心怎么执行操作
windows安全中心怎么关闭 windows安全中心怎么执行操作

关闭Windows安全中心(Windows Defender)可通过系统设置暂时关闭,或使用组策略/注册表永久关闭。最简单的方法是:进入设置 > 隐私和安全性 > Windows安全中心 > 病毒和威胁防护 > 管理设置,将实时保护等选项关闭。

4

2026.01.26

2026年春运抢票攻略大全 春运抢票攻略教你三招手【技巧】
2026年春运抢票攻略大全 春运抢票攻略教你三招手【技巧】

铁路12306提供起售时间查询、起售提醒、购票预填、候补购票及误购限时免费退票五项服务,并强调官方渠道唯一性与信息安全。

20

2026.01.26

个人所得税税率表2026 个人所得税率最新税率表
个人所得税税率表2026 个人所得税率最新税率表

以工资薪金所得为例,应纳税额 = 应纳税所得额 × 税率 - 速算扣除数。应纳税所得额 = 月度收入 - 5000 元 - 专项扣除 - 专项附加扣除 - 依法确定的其他扣除。假设某员工月工资 10000 元,专项扣除 1000 元,专项附加扣除 2000 元,当月应纳税所得额为 10000 - 5000 - 1000 - 2000 = 2000 元,对应税率为 3%,速算扣除数为 0,则当月应纳税额为 2000×3% = 60 元。

9

2026.01.26

oppo云服务官网登录入口 oppo云服务登录手机版
oppo云服务官网登录入口 oppo云服务登录手机版

oppo云服务https://cloud.oppo.com/可以在云端安全存储您的照片、视频、联系人、便签等重要数据。当您的手机数据意外丢失或者需要更换手机时,可以随时将这些存储在云端的数据快速恢复到手机中。

14

2026.01.26

抖币充值官方网站 抖币性价比充值链接地址
抖币充值官方网站 抖币性价比充值链接地址

网页端充值步骤:打开浏览器,输入https://www.douyin.com,登录账号;点击右上角头像,选择“钱包”;进入“充值中心”,操作和APP端一致。注意:切勿通过第三方链接、二维码充值,谨防受骗

6

2026.01.26

热门下载

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

精品课程

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

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