In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the difference between BIO, NIO and AIO in Java". The content in the article is simple and clear, easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the difference between BIO, NIO and AIO in Java".
IO
What is IO? It refers to the interface between the computer and the outside world or between a program and the rest of the computer. It is critical to any computer system, so all the bodies of Iripple O are actually built into the operating system. Separate programs generally let the system do most of the work for them.
In Java programming, streaming has until recently been used to accomplish Imax O. All Stream O is treated as a single byte movement, one byte at a time through an object called petabyte. Stream IPUBO is used for contact with the outside world. It is also used internally to convert the object to bytes and then back to the object.
BIO
Java BIO is Block IO O, synchronized and blocked.
BIO is the code implementation under the traditional java.io package.
NIO
What is NIO? NIO has the same function and purpose as the original Imax O, and the most important difference between them is the way data is packaged and transmitted. The original NIO O processes data in a streaming manner, while it processes data in blocks.
The stream-oriented IWeiO system processes data one byte at a time. An input stream produces one byte of data, and an output stream consumes one byte of data. It is very easy to create filters for streaming data. It is also relatively simple to link several filters so that each filter is responsible for only part of a single complex processing mechanism. The downside is that stream-oriented I _ map O is usually quite slow.
A block-oriented Istroke O system processes data in the form of blocks. Each operation generates or consumes a block of data in one step. Processing data by blocks is much faster than by (streaming) bytes. However, the block-oriented Iamp O lacks some of the elegance and simplicity of the stream-oriented Imax O.
AIO
Java AIO is Async non-blocking, which is asynchronous non-blocking IO.
Difference and relation
BIO (Blocking Blocking O): synchronously blocks the Imax O mode, where reads and writes to data must be blocked in a thread waiting for it to complete. Suppose a scene of boiling water, where there is a row of kettles boiling water. BIO works by asking a thread to stay at a kettle until the kettle boils before dealing with the next kettle. But the thread actually did nothing while waiting for the kettle to boil.
NIO (New non-blocking O): supports both blocking and non-blocking modes, but here we illustrate with its synchronous non-blocking I-sign O mode, so what is synchronous non-blocking? If you also take boiling water as an example, NIO's practice is to ask a thread to constantly poll the status of each kettle to see if the state of the kettle has changed, so as to proceed to the next step.
AIO (Asynchronous Imax O): asynchronous non-blocking Imax O model. What is the difference between asynchronous nonblocking and synchronous nonblocking? Asynchronous non-blocking does not require a thread to poll for state changes in all IO operations. After the corresponding state changes, the system will notify the corresponding threads to handle them. Corresponding to the boiling water, a switch is installed on each kettle, and after the water is boiled, the kettle will automatically inform me that the water is boiling.
Their respective applicable scenarios
The BIO method is suitable for the architecture with a small number of connections and a fixed number of connections, which requires high server resources, and concurrency is limited to the application. JDK1.4 is the only choice before, but the program is intuitive, simple and easy to understand.
NIO is suitable for architectures with a large number of connections and short connections (light operation), such as chat servers, where concurrency is limited to applications, programming is more complex, and JDK1.4 begins to support it.
AIO is suitable for architectures with a large number of connections and long connections (re-operation), such as photo album server, fully calling OS to participate in concurrent operations, programming is more complex, and JDK7 begins to support it.
Mode of use
Use BIO to read and write files.
/ / Initializes The Object User1 user = new User1 (); user.setName ("hollis"); user.setAge (23); System.out.println (user); / / Write Obj to File ObjectOutputStream oos = null; try {oos = new ObjectOutputStream (new FileOutputStream ("tempFile")); oos.writeObject (user) } catch (IOException e) {e.printStackTrace ();} finally {IOUtils.closeQuietly (oos);} / / Read Obj from File File file = new File ("tempFile"); ObjectInputStream ois = null; try {ois = new ObjectInputStream (new FileInputStream (file)); User1 newUser = (User1) ois.readObject () System.out.println (newUser);} catch (IOException e) {e.printStackTrace ();} catch (ClassNotFoundException e) {e.printStackTrace ();} finally {IOUtils.closeQuietly (ois); try {FileUtils.forceDelete (file) } catch (IOException e) {e.printStackTrace ();}} / / Initializes The Object User1 user = new User1 (); user.setName ("hollis"); user.setAge (23); System.out.println (user); / / Write Obj to File ObjectOutputStream oos = null Try {oos = new ObjectOutputStream (new FileOutputStream ("tempFile")); oos.writeObject (user);} catch (IOException e) {e.printStackTrace ();} finally {IOUtils.closeQuietly (oos);} / / Read Obj from File File file = new File ("tempFile"); ObjectInputStream ois = null Try {ois = new ObjectInputStream (new FileInputStream (file)); User1 newUser = (User1) ois.readObject (); System.out.println (newUser);} catch (IOException e) {e.printStackTrace ();} catch (ClassNotFoundException e) {e.printStackTrace ();} finally {IOUtils.closeQuietly (ois) Try {FileUtils.forceDelete (file);} catch (IOException e) {e.printStackTrace ();}}
Use NIO to read and write files.
Static void readNIO () {String pathname = "C:\\ Users\\ adew\\ Desktop\\ jd-gui.cfg"; FileInputStream fin = null; try {fin = new FileInputStream (new File (pathname)); FileChannel channel = fin.getChannel (); int capacity = 100 / / Byte ByteBuffer bf = ByteBuffer.allocate (capacity); System.out.println ("limit is:" + bf.limit () + "capacity is:" + bf.capacity () + "position is:" + bf.position ()); int length =-1 While ((length = channel.read (bf))! =-1) {/ * * Note: after reading, set the position to 0 and limit to the capacity for next time to read into the byte buffer. Store * / bf.clear () from 0 Byte [] bytes = bf.array (); System.out.write (bytes, 0, length); System.out.println () System.out.println ("limit is:" + bf.limit () + "capacity is:" + bf.capacity () + "position is:" + bf.position ());} channel.close () } catch (FileNotFoundException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace () } finally {if (fin! = null) {try {fin.close ();} catch (IOException e) {e.printStackTrace () }} static void writeNIO () {String filename = "out.txt"; FileOutputStream fos = null; try {fos = new FileOutputStream (new File (filename)) FileChannel channel = fos.getChannel (); ByteBuffer src = Charset.forName ("utf8"). Encode ("Hello") / / Byte buffer capacity and limit vary with data length, not fixed System.out.println ("initialization capacity and limit:" + src.capacity () + "," + src.limit ()); int length = 0 " While ((length = channel.write (src))! = 0) {/ * * Note, clear is not needed here Write the buffered data to the channel for the second time and then read down * / System.out.println in the previous order ("write length:" + length) }} catch (FileNotFoundException e) {e.printStackTrace ();} catch (IOException e) {e.printStackTrace () } finally {if (fos! = null) {try {fos.close ();} catch (IOException e) {e.printStackTrace () }}
Using AIO to read and write files
Public class ReadFromFile {public static void main (String [] args) throws Exception {Path file = Paths.get ("/ usr/a.txt"); AsynchronousFileChannel channel = AsynchronousFileChannel.open (file); ByteBuffer buffer = ByteBuffer.allocate (100000000); Future result = channel.read (buffer, 0); while (! result.isDone ()) {ProfitCalculator.calculateTax ();} Integer bytesRead = result.get () System.out.println ("Bytes read [" + bytesRead + "]");} class ProfitCalculator {public ProfitCalculator () {} public static void calculateTax () {}} public class WriteToFile {public static void main (String [] args) throws Exception {AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open (Paths.get ("/ asynchronous.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE) CompletionHandler handler = new CompletionHandler () {@ 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 e, Object attachment) {System.err.println ("Attachment:" + attachment + "failed with:"); e.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)}} Thank you for reading. The above is the content of "what is the difference between BIO, NIO and AIO in Java". After the study of this article, I believe you have a deeper understanding of the difference between BIO, NIO and AIO in Java, and the specific use needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.