Recently studied Java NiO as well as threading concurrency, made a point of thinking, special notes as follows (NiO article) __java

Source: Internet
Author: User
Tags message queue
Original post address: http://www.cnblogs.com/feidao/archive/2005/07/15/193788.html recently studied Java NiO as well as threading concurrency, made a point of thinking, special notes as follows (NiO article)

Because the previous project needs to write a number of high-performance servers, the results are written in a variety of results, we require the use of NIO to write asynchronous server, but unexpectedly someone put NiO abruptly written in sync, but also written a single batch processing, thread scheduling, communication, synchronization operations, such as unrestrained, See no architecture, typical noodle code, extremely faint, have to make up your mind, the IO part and the thread scheduling part of the isolation.
To this end, ruthless, carefully studied the NIO mechanism and DL of the Util.concurrent package.

First, the emergence of NIO
NiO is the JDK1.4 inside of the east, and he brings the greatest benefit to everyone is asynchronous socket. The other file,pipe will not talk much for a while.
Before JDK1.4 appears, if you need to write a Java server, in order to achieve asynchronous operation, you must generate a Java thread for each connection request, when a lot of connection requests, thread scheduling, context switching, the cost is very expensive, and because Java is cross-platform, the platform for the support of the thread is not the same, Performance is also not the same, so the traditional Java server programming architecture is inefficient and expensive, after the DL Master wrote a util.concurrent package, finally reduce the thread scheduling to the Java programmer pain, but compared with C, C + + written out of the server, The Java server in the case of high performance requirements, basically no competitive, even the right to be shortlisted.

Implementation of asynchronous socket
After the appearance of NiO, it seems that Java programmers have the opportunity to Yang Yi, how to Exhale, what people were feeling at that time, I do not know, because I do not engage in Java, the knowledge of Java is limited.
NIO is an event-based IO architecture, and the basic idea is that when there are events I tell you, you do your thing, you can save a lot of time doing anything else when there's no event. and the main thread of NIO, unlike the traditional model, takes n threads and eases the workload of the JVM, making it more efficient for the JVM to process tasks.
When the first contact with NIO, by the N-tier channel architecture, the internet overwhelming acclaim, think it should be a very mature products, online information so much, copy a copy of jetty, Tomcat and other cattle b source code, basically can be done, At this time did not think everyone is affected by the synchronization so deep, also did not think that even the most basic asynchronous concepts are not clear to write code, to create a bunch of problems (this is something, back to say).
Now, after studying NIO, the discovery that NiO actually does in Java is very simple, that is, the collection and distribution of events, we combine a classic invocation example to illustrate the problem, I do not start from the basic use of NIO, you can look for other information, online a lot.
When channel is registered to selector, our most classical method of invocation is this.
1 while (somecondition)
2 {
3 int n = selector.select (TIMEOUT);
4 if (n = = 0) continue;
5 for (Iterator iter = Selector.selectedkeys (). iterator (); Iter.hasnext ();)
6 {
7 if (key.isacceptable ())
8 doacceptable (key);
9 if (key.isconnectable ())
Ten doconnectable (key);
One if (Key.isvalid () && key.isreadable ())
Doreadable (key);
if (Key.isvalid () && key.iswritable ())
Dowritable (key);
Iter.remove ();
16}
17}

This is just a small example ah, anything unusual I don't bother to catch.
The event notification in NiO is done in the selector select event, and there is a thread in the selector event, which is specifically handled simply by asking the operating system, selector registered channel&& Selectionkey pairs of events have occurred, if any have been added to Selector's Selectedkeys property set, and return the number of interesting things happen this time. The programmer discovers this value >0, indicates that has the event occurrence, immediately iterates Selectedkeys in the Selectionkey, according to the event which in the key expresses, does the corresponding processing.
In fact, this description shows the core of the asynchronous socket, that is, the asynchronous socket is simply the dispatch of multiple sockets (or even their thread scheduling) to the operating system to complete their own, asynchronous core selector, but the dispatch of these dispatches only to collect and distribute. Because of the operating system socket, thread scheduling and then D is better than your JVM, high efficiency.
And even if the JVM does as well as the operating system, and the performance is as high (which is unrealistic, of course), you can save at least half of the system consumption using asynchronous sockets, and imagine that the operating system itself is using threads to maintain n socket connections, and in traditional Java programming, You must also have a Java thread for these sockets, which is at least 2N threads and now requires only n+ 1. In the case of high concurrency, think about it yourself.
Understand this truth, asynchronous socket is good to write, also will not get confused thinking.

What should be paid attention to in asynchronous socket
3.1 Read
Asynchronous socket The most basic idea is the event notification, said earlier, there are events to inform you, you should do what you should do. In asynchronous socket when a Op_read event is registered, you wait for selector to inform you, if you are not informed, you can sleep at home.
Here, one of our mistakes is to be affected by synchronization, to read their own initiative, but also out of multithreading, if you think about it, this problem will not occur. In a synchronous socket, when the Read method is invoked to read data in Io, the Read method is thread-safe when multiple threads are accessed simultaneously, usually if no data read method blocks and is synchronized.
And asynchronous is different, asynchronous is not blocked, have anything to return what, you take the initiative to read, as long as there is data, you can take away, in the case of multithreading, you may want to let the first thread read, but at this time to data is exactly the thread 2 read, that thread 2 happily take it, and thread 1 is still waiting, so that data chaos does not say, if the following no more data, thread 1 is dead cycle.

2. Write
In asynchronous socket, write is the only one active point of operation, but also can not directly to write Channel, but should first register itself as op_writable, then selector will find your existence, and send a write event, you can then write, But there is a small trick, that is, before you perform a write operation, please cancel your write registration, otherwise your CPU must be 100%.

3. Waiting for
In traditional server programming, because each request is generated by a thread, so you wait in each of your request thread, sleep or not affect others. But unlike asynchronous, his main thread has only one, basically each processing is linear, that is, processing the first, and then processing the second, so NiO is an excellent way to deal with short connection architecture.
The problem we're having now is, someone is affected by synchronization, do not know how asynchronous is handled, even in the method of using sleep, and 3 seconds, what this means, 3 seconds to process a request, my God, I want a 3 seconds to process a request server why Ah, Or the 60 's AH: (
If there is such a need to wait for the situation, you should start another thread (the thread pool is recommended) to complete this "long" time task, or the other to a message queue, through the way to send messages to others to complete the line, the client can wait, how can you wait for the server. Write such a code, basically a server is also obsolete.

This blog I hair in the personal mood essay, a little grumble, it is felt for some people's thinking that some incredible, do not spit unhappy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.