Java NIO Learning Series Six: Java in the IO model

  Earlier , we summarize the 5 IO model linux system, and focuses on the four kinds of IO models of them:

  • Blocking I / O (blocking IO)
  • Non-blocking I / O (nonblocking IO)
  • I / O multiplexer (IO multiplexing)
  • Asynchronous I / O (asynchronous IO)

  But the summary of the previous IO model is only limited concept under linux, more biased in favor of the underlying operating system, and not related to the Java application level, in fact, Java also provides a conceptual and IO model in front of the operating system level corresponding to this is the next focus of this paper talk.

  The same paper will be launched around the following points:

  I / O model corresponds in Java

  Applicable scene

  Java in a variety of ways using the IO model

  to sum up

 

1. I / O model corresponds in Java

1.1 blocking I / O

  Thread traditional Java IO IO mode of operation to provide stream-oriented belongs to blocking, and call its read () or write () method will block until the completion of the reading and writing of data in the process of reading and writing in what is both a thread I can not do.

1.2 Non-blocking I / O

  When the Java NIO libraries to support non-blocking mode offers a variety of classes, such as Channel, Buffer, you can set it to non-blocking mode, thread requests to read data channel, the data will only get ready, and will not clog with waiting for all the data are ready, so that at the stage of preparation of thread data can be to deal with something else, which is non-blocking read, to write data is the same.

  And here is the difference between the above-blocking, calling read () or write () method does not block, but returns immediately, but this time the IO operation is often not the end.

1.3 Multiplexer

  Java NIO Selector allows a single thread of multiple channel monitoring, you can register multiple channel into a Selector, and then you can "select" a good channel data has been prepared, or ready channel well written, and then read them or writing data, which is multiplexed.

1.4 Asynchronous IO

   Asynchronous IO IO model is an ideal model, asynchronous IO model, after you read the thread to initiate operation, you can immediately start to do other things. On the other hand, the kernel will wait for data preparation is complete, then copy the data to the user thread, when it's all finished, the user kernel threads will send a signal telling it read operation is complete. Which means that users do not care about the actual thread completely whole IO operations, and only need to initiate requests on the line, when the signal is received successfully kernel can go directly to the use of the data. This is the difference between non-blocking and, if blocking IO is entirely manual, non-blocking IO is semi-automatic, and automatic asynchronous IO is, multiplexing it? I think we can be semi-automatic assault rifles ^ _ ^

  In Java 7, it provides Asynchronous IO, Java NIO in AsynchronousFileChannel support asynchronous model implementation.

 

2. Applicable scene

  BIO method is applicable to a relatively small number of connections and each take up a lot broadband connection, this way of server resource requirements are relatively high, JDK1.4 previously the 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, 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.

 

3. Java in a variety of ways using the IO model

  Speaking in front of so many, that talked about IO model under linux, and spoke in Java support for these IO models, and here I think it's time to find some practical examples to see in Java, the following were in three IO model to read and write files.

3.1 to read and write files BIO way

  public void rwByBIO() {
    BufferedReader br = null;
    FileInputStream in = null;
    FileOutputStream out = null;
    try {
      in = new FileInputStream("test.txt");
      out = new FileOutputStream("testBIO.txt");
      List<Integer> list = new ArrayList();
      int temp;
      while((temp = in.read()) != -1) {
        out.write(temp);
      }
      br = new BufferedReader(new InputStreamReader(new FileInputStream("testBIO.txt")));
      System.out.println(br.readLine());
    }catch(Exception e) {
      e.printStackTrace();
    }finally {
      if(br != null) {
        try {
          br.close();
        }catch(IOException e) {
          e.printStackTrace();
        }
      }
      if(out != null) {
        try {
          out.close();
        }catch(IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  Ready at the root of good file test.txt, which is written on the prepared content, such as "yellow sand battle to wear shining armor, not broken Loulan not also," then run, then you should be more than a file testBIO.txt , which content is the same. We read the contents of test.txt by BIO way, the same way BIO written to testBIO.txt in.

3.2 by NIO read and write files

  public void rwByNIO() {
    FileChannel readChannel = null;
    FileChannel writeChannel = null;
    try {
      readChannel = new RandomAccessFile(new File("test.txt"),"r").getChannel();
      writeChannel = new RandomAccessFile(new File("testNIO.txt"),"rw").getChannel();
      ByteBuffer buffer = ByteBuffer.allocate(10);
      int bytesRead = readChannel.read(buffer);
      while(bytesRead != -1) {
        buffer.flip();
        while(buffer.hasRemaining()) {
          // 写入文件
          writeChannel.write(buffer);
        }
        // 一次写完之后
        buffer.clear();
        bytesRead = readChannel.read(buffer);
      }
    }catch(Exception e) {
      e.printStackTrace();
    }finally {
      if(readChannel != null) {
        try {
          readChannel.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if(writeChannel != null) {
        try {
          writeChannel.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  Here it is to read and write by the NIO FileChannel file, but be aware that although the title of this section is to say by way of the NIO to read and write files, but FileChannel does not support non-blocking mode, so it is actually still belongs to obstruction that BIO's way, just as an example here to demonstrate the unified read and write files, it is still in use FileChannel class NIO to complete.

Read and write files by way of AIO 3.3

    public void rwByAIO() {
        Path path = Paths.get("test.txt");
        AsynchronousFileChannel fileChannel = null;
        try {
            fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            long position = 0;
            Future<Integer> operation = fileChannel.read(buffer, position);
            while(!operation.isDone());
            buffer.flip();
            Path writePath = Paths.get("testAIO.txt");
            if(!Files.exists(writePath)){
                Files.createFile(writePath);
            }
            AsynchronousFileChannel writeFileChannel = AsynchronousFileChannel.open(writePath, StandardOpenOption.WRITE);

            writeFileChannel.write(buffer, position, buffer, new CompletionHandler<Integer, ByteBuffer>() {

                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    System.out.println("bytes written: " + result);
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    System.out.println("Write failed");
                    exc.printStackTrace();
                }
            });
          
        }catch(Exception e) {
          e.printStackTrace();
        }
      }

  This example is to read and write files asynchronously manner. When you call a Java NIO in AsynchronousFileChannel such operations provide support, when you call its read () method will immediately return a Future object by calling its isDone way to know whether the data has been read.

 

4. to sum up

  Combining IO model mentioned hereinbefore, corresponding to the specific Java class library, and demonstrates BIO, NIO, AIO read and write files by way of example three ways.

  • Way standard Java IO provides stream-oriented model of the attainment of BIO, it will clog in the process of reading;
  • After the Java NIO Buffer provided Channel and is supported NIO mode, reading and writing method called Channel can return immediately, in the process of preparing the data to the Buffer is not blocked, the thread can do other things, but read from Buffer write data is blocked;
  • AsynchronousFileChannel support asynchronous read and write files Java NIO provided, after calling its read and write methods can return immediately, only need to wait for the system to copy the data to the specified location can be, the whole process will not be blocked;

 

references

bio-vs-nio-vs-going

linux-I

Guess you like

Origin www.cnblogs.com/volcano-liu/p/11185574.html