In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to realize Java NIO ready mode". In daily operation, I believe many people have doubts about how to realize Java NIO ready mode. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to realize Java NIO ready mode". Next, please follow the editor to study!
Java NIO non-blocking applications are usually suitable for Imax O read and write, we know that the performance bottleneck of the system is usually in Imax O read and write, including the operation of ports and files. In the past, after opening an I Unip O channel, read () would always wait on the port side to read byte content, if no content came in, read () would also be silly, etc., which would affect our program to continue to do other things. Then the improvement is to set up a thread and let the thread wait, but this is also quite resource-consuming.
Java NIO non-blocking technology actually adopts Reactor mode, or Observer mode, to monitor the Icano port for us. If anything comes in, it will automatically notify us, so that we do not have to open multiple threads to die, and so on. From the outside, it has achieved smooth Icano read and write without blocking.
The emergence of Java NIO is not just a technical performance improvement, you will find it everywhere on the network, because it is a milestone. Starting from JDK1.4, Java began to improve performance-related functions, so that Java can keep pace with C or Perl in underlying or parallel distributed computing and other operations.
Fig. 1 class structure diagram
Package cn.chenkangxian.nioconcurrent; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.LinkedList; import java.util.List; / * * @ Project: testNio * * @ Author: chenkangxian * * @ Annotation: use thread pool to handle a large number of channel concurrency * * @ Date:2011-7-5 * * @ Copyright: 2011 chenkangxian, All rights reserved. * * / public class SelectSocketsThreadPool extends SelectSockets {private static final int MAX_THREADS = 5; private ThreadPool pool = new ThreadPool (MAX_THREADS); / * read data from socket * / protected void readDataFromSocket (SelectionKey key) throws Exception {WorkerThread worker = pool.getWorker (); if (worker = = null) {return; worker.serviceChannel (key) } / * * @ Project: concurrentnio * @ Author: chenkangxian * * @ Annotation: thread pool * * @ Date:2011-7-20 * * @ Copyright: 2011 chenkangxian, All rights reserved. * * / private class ThreadPool {List idle = new LinkedList (); / * * Thread pool initialization * * @ param poolSize Thread Pool size * / ThreadPool (int poolSize) {for (int I = 0; I)
< poolSize; i++) { WorkerThread thread = new WorkerThread(this); thread.setName("Worker" + (i + 1)); thread.start(); idle.add(thread); } } /** * 获得工作线程 * * Author: chenkangxian * * Last Modification Time: 2011-7-20 * * @return */ WorkerThread getWorker() { WorkerThread worker = null; synchronized (idle) { if (idle.size() >0) {worker = (WorkerThread) idle.remove (0);}} return (worker) } / * send back worker thread * * Author: chenkangxian * * Last Modification Time: 2011-7-20 * * @ param worker * / void returnWorker (WorkerThread worker) {synchronized (idle) {idle.add (worker) } private class WorkerThread extends Thread {private ByteBuffer buffer = ByteBuffer.allocate (1024); private ThreadPool pool; private SelectionKey key; WorkerThread (ThreadPool pool) {this.pool = pool;} public synchronized void run () {System.out.println (this.getName () + "is ready") While (true) {try {this.wait (); / / waiting to be notify} catch (InterruptedException e) {e.printStackTrace (); this.interrupt () } if (key = = null) {/ / until key continue;} System.out.println (this.getName () + "has been awakened"); try {drainChannel (key) } catch (Exception e) {System.out.println ("Caught'" + e + "'closing channel"); try {key.channel (). Close ();} catch (IOException ex) {ex.printStackTrace ();} key.selector () .wakeup () } key = null; this.pool.returnWorker (this);}} synchronized void serviceChannel (SelectionKey key) {this.key = key; / / eliminate read concerns key.interestOps (key.interestOps () & (~ SelectionKey.OP_READ)); this.notify () } void drainChannel (SelectionKey key) throws Exception {SocketChannel channel = (SocketChannel) key.channel (); int count; buffer.clear (); while ((count = channel.read (buffer)) > 0) {buffer.flip (); while (buffer.hasRemaining ()) {channel.write (buffer) } buffer.clear ();} if (count
< 0) { channel.close(); return; } //重新开始关注读事件 key.interestOps(key.interestOps() | SelectionKey.OP_READ); key.selector().wakeup(); } } public static void main(String[] args) throws Exception { new SelectSocketsThreadPool().go(args); } }package cn.chenkangxian.nioconcurrent; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.ByteBuffer; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; /** * * @Project: concurrentnio * * @Author: chenkangxian * * @Annotation: * * @Date:2011-7-11 * * @Copyright: 2011 chenkangxian, All rights reserved. * */ public class SelectSockets { public static int PORT_NUMBER = 1234; private ByteBuffer buffer = ByteBuffer.allocate(1024); public static void main(String[] args) throws Exception { new SelectSockets().go(args); } public void go(String[] args) throws Exception{ int port = PORT_NUMBER; // if(args.length >0) {/ / port = Integer.parseInt (args [0]); / /} / / System.out.println ("Listening on port" + port); ServerSocketChannel serverChannel = ServerSocketChannel.open (); ServerSocket serverSocket = serverChannel.socket (); Selector selector = Selector.open (); serverSocket.bind (new InetSocketAddress (port)); serverChannel.configureBlocking (false) ServerChannel.register (selector, SelectionKey.OP_ACCEPT); while (true) {int n = selector.select (); / / No polling, single selector if (n = = 0) {continue;} Iterator it = selector.selectedKeys () .iterator () While (it.hasNext ()) {SelectionKey key = (SelectionKey) it.next (); if (key.isAcceptable ()) {ServerSocketChannel server = (ServerSocketChannel) key.channel (); SocketChannel channel = server.accept (); registerChannel (selector,channel,SelectionKey.OP_READ) SayHello (channel);} if (key.isReadable ()) {readDataFromSocket (key);} it.remove () } / * register channel on selector And set interest * * Author: chenkangxian * * Last Modification Time: 2011-7-11 * * @ param selector selector * * @ param channel channel * * @ param ops interest * * @ throws Exception * / protected void registerChannel (Selector selector, SelectableChannel channel Int ops) throws Exception {if (channel = = null) {return } channel.configureBlocking (false); channel.register (selector, ops) } / * deal with available data channels * * Author: chenkangxian * * Last Modification Time: 2011-7-11 * * @ param key key * * @ throws Exception * / protected void readDataFromSocket (SelectionKey key) throws Exception {SocketChannel socketChannel = (SocketChannel) key.channel (); int count Buffer.clear (); / / Empty buffer while ((count = socketChannel.read (buffer)) > 0) {buffer.flip (); while (buffer.hasRemaining ()) {socketChannel.write (buffer);} buffer.clear ();} if (count < 0) {socketChannel.close () Author: chenkangxian * * Last Modification Time: 2011-7-11 * * @ param channel client channel * * @ throws Exception * / private void sayHello (SocketChannel channel) throws Exception {buffer.clear () Buffer.put ("Hello Hello!\ r\ n" .getBytes ()); buffer.flip (); channel.write (buffer);}} at this point, the study on "how to implement the Java NIO Readiness Model" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.