BIO, NIO and AIO acquaintance and code implementation

Brief introduction

The IO, collaboration often I / O, is Input / Output short, i.e., input / output. It refers generally to input and output data between the internal memory (RAM) and an external memory (hard disk, USB, etc.) or other peripheral devices.

Communication I / O is an information processing system (e.g. a computer) with the outside world (which may be a human or another information processing system) between.

Is the system receives input signals or data, or the data output signal therefrom is transmitted.

In Java, it provides some columns API, can be used by developers to read and write data or external files. We call these API for the Java IO.

IO in Java is more important, and more difficult knowledge points, mainly because with the development of Java, there are three IO coexist. They are BIO, NIO and AIO.

Java BIO

BIO Full Block-IO is a synchronous and blocking communication mode. Is a more traditional means of communication, mode is simple, easy. But the low concurrent processing, the communication time consuming, depending on the network speed.

Java NIO

Java NIO, the whole Non-Block IO, a later version of Java SE 1.4, for network transmission performance optimization of new features. A synchronous non-blocking mode of communication.

NIO with the original I / O has the same effect and purpose, the most important difference between them is the data package and transmission. The original I / O data in a stream manner, in the manner and NIO data processing blocks.

Stream-oriented I / O system processing one byte of data. An input stream generating a data byte, a data byte of a consumption output stream.

Block-oriented I / O system processing data in blocks. Each operation to generate a data block, or consumption in one step. Processing the data in blocks by ratio (flow type) bytes of data to be processed faster. However, block-oriented I / O lacks some stream-oriented I / O and has elegant simplicity.

Java AIO

Java AIO, full Asynchronous IO, is asynchronous non-blocking of IO. Is a non-blocking communication asynchronous mode.

NIO on the basis of the introduction of a new concept of asynchronous channels and provides asynchronous file channel and asynchronous socket channel.

Distinguish three IO's

First of all, we stand a macro point of view, to re-draw the main points:

BIO (Blocking I / O): synchronous blocking I / O mode.

NIO (New I / O): Synchronous non-blocking mode.

AIO (Asynchronous I / O): non-blocking asynchronous I / O model.

Synchronous blocking mode: In this mode, we work is to come to the kitchen and began to boil water, and sitting in front of the kettle has been waiting for water to boil.

Synchronous non-blocking mode: In this mode, we work is to come to the kitchen and began to boil water, but we have not been sitting in front of the kettle, but returned to the living room watching TV, and then every few minutes to look at the kitchen there is no water about to boil.

Asynchronous non-blocking I / O model: In this model, our model is the first work went to the kitchen and began to boil water, not we been sitting in front of the kettle, nor take a look from time to time, but in the living room watching TV, there is a switch on top of the kettle, boil water after he'd let me know.

VS blocking non-blocking: whether the person sitting in front of the kettle has been waiting for.

Synchronous asynchronous VS: kettle is not actively inform people after the water to a boil.

Applicable scene

The number of connected mode applies to relatively small BIO and fixed architecture, server resources in this way is relatively high, limited concurrent applications, the JDK1.4 previously only option, but the program intuitive and easy to understand.

NIO connection number suitable for multi-mode and connected to short (light operation) architecture, such as chat server, limited concurrent applications, more complex programming, starts the JDK1.4 support.

AIO method is applicable to more than the number of connections and the connection is relatively long (heavy operation) architecture, such as the album server, call the OS to fully participate in concurrent operation, programming is more complex, JDK7 began to support.

Use BIO achieve read and write files.

    @Test
    public void write() {
        Person person = Person.builder().id(1L).name("谢飞").build();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("E://a.txt"));
            oos.writeObject("ad");
            System.out.println("文件已存入");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(oos);
        }
    }

    @Test
    public void read() {
        File file = new File("a.txt");
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(file));
            Person person = (Person) ois.readObject();
            System.out.println(person);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(ois);
            try {
                FileUtils.forceDelete(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Use NIO achieve read and write files.

package com.zoo.lion.modules.test.io;

import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * @Author: xf
 * @Date: 2019/7/8 16:46
 * @Version 1.0
 */
public class NIO {
    private static final String pathname = "E://a.txt";

    @Test
    public void write() {
        try (FileInputStream fin = new FileInputStream(new File(pathname))) {
            FileChannel channel = fin.getChannel();
            int capacity = 100;// 字节
            ByteBuffer bf = ByteBuffer.allocate(capacity);
            int length;
            while ((length = channel.read(bf)) != -1) {
                bf.clear();
                byte[] bytes = bf.array();
                System.out.write(bytes, 0, length);
                System.out.println();
            }
            channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void writeNIO() {
        try (FileOutputStream fos = new FileOutputStream(new File(pathname))) {
            FileChannel channel = fos.getChannel();
            ByteBuffer src = Charset.forName("utf8").encode("你好你好你好你好你好");
            int length;
            while ((length = channel.write(src)) != 0) {
                System.out.println("写入长度:" + length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

Use AIO achieve read and write files

package com.zoo.lion.modules.test.io;

import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

/**
 * @Author: xf
 * @Date: 2019/7/9 14:00
 * @Version 1.0
 */
public class AIO {
    private static final String pathname = "E://a.txt";

    @Test
    public void write() throws Exception {
        AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(
                Paths.get(pathname), StandardOpenOption.READ,
                StandardOpenOption.WRITE, StandardOpenOption.CREATE);

        CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {
            @Override
            public void completed(Integer result, Object attachment) {
                System.out.println("Attachment: " + attachment + " " + result
                        + " bytes written");
                System.out.println("CompletionHandler Thread ID: "
                        + Thread.currentThread().getId());
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                System.err.println("Attachment: " + attachment + " failed with:");
                exc.printStackTrace();
            }
        };
        System.out.println("Main Thread ID: " + Thread.currentThread().getId());
        fileChannel.write(ByteBuffer.wrap("Sample".getBytes()), 0, "First Write",
                handler);
        fileChannel.write(ByteBuffer.wrap("Box".getBytes()), 0, "Second Write",
                handler);
    }

    @Test
    public void read() throws Exception {
        Path file = Paths.get(pathname);
        AsynchronousFileChannel channel = AsynchronousFileChannel.open(file);
        ByteBuffer buffer = ByteBuffer.allocate(100_000);
        Future<Integer> result = channel.read(buffer, 0);
        while (!result.isDone()) {
            ProfitCalculator.calculateTax();
        }
        Integer bytesRead = result.get();
        System.out.println("Bytes read [" + bytesRead + "]");
    }

    static class ProfitCalculator {
        public ProfitCalculator() {
        }

        static void calculateTax() {
        }
    }


}

(Finish)

Guess you like

Origin blog.csdn.net/qq_36850813/article/details/95191694