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 iterable = Arrays.asList("Hello", "world"); Files.write(path, iterable); byte[] bytes = Files.readAllBytes(path); System.out.println(new String(bytes)); } } 登录后复制