Synchronous and asynchronous Java

Source: Internet
Author: User

The asynchronous input/output mechanism means that the input/output processing does not have to wait until the input/output processing is complete. Therefore, asynchronous synonyms are non-blocking (none blocking ).

 

On the Internet, many netizens use a very popular metaphor to thoroughly explain synchronization and Asynchronization.

 

For example: Normal B/S mode (synchronous) Ajax technology (asynchronous)
Synchronization: submit a request, wait for the server to process, and return the result. The client browser cannot do anything during this period.
Asynchronous: requests are triggered through events-> server processing (this is what the browser can do)-> processing is complete

 

Synchronization means that you ask me to go to dinner. When I hear it, I will go to dinner with you. If I don't hear it, you will not stop calling until I tell you to hear it.
Asynchronous mode means that you call me and then eat on your own. After receiving the message, I may leave immediately or wait until I get off work.
Therefore, if I want to invite you to dinner, I will use the synchronous method. If I want to invite you to dinner, I will use the asynchronous method, so that you can save money.

 

 

Take communication as an Example
Synchronization: send a request, wait for the return, and then send the next request
Asynchronous: send a request. You can send the next request at any time without waiting for the response.
Concurrency: send multiple requests at the same time

 

 

 

Next, let's take a lookJavaArticles about asynchronous applications

 

Write a socket process communication program using an asynchronous input/output stream

Added the application interface package for implementing asynchronous input/output Mechanism in Merlin: Java. niO (a new input/output package that defines many basic types of buffer), Java. NIO. channels (channels and selectors, used for asynchronous input and output), Java. NIO. charset (character encoding and decoding ). Channel first registers events of interest in the selector. when an event occurs, the selectionkey is used to notify the registered channel. Then, the channel packages the information to be processed, encodes and decodes it, and controls the input and output.

Channel introduction:

Here we mainly introduce serversocketchannel and socketchannel. they are all selectable (selectable) channels, which can work in both synchronous and asynchronous modes (Note: The options here do not mean that you can select two working modes, you can register events that you are interested in ). You can use channel. configureblocking (Boolean) to set the working mode. Compared with APIs of previous versions, serversocketchannel is equivalent to serversocket
(Serversocketchannel encapsulates serversocket), while socketchannel is equivalent to socket (socketchannel encapsulates socket ). When the channel is working in synchronization mode,ProgrammingThe method is similar to the previous one. Here we mainly introduce the asynchronous working method.

The asynchronous input/output mechanism means that the input/output processing does not have to wait until the input/output processing is complete. Therefore, asynchronous synonyms are non-blocking (none blocking ). On the server side, serversocketchannel returns an instance of serverchlorophyll through the static function open. Then, this channel calls serverchlorophyll. socket (). BIND () to a port on the server, and call register (selector Sel, selectionkey. op_accept) registers the op_accept event to a selector (serversocketchannel can only register the op_accept event ). When a customer requests a connection, the selector notifies the channel that a customer connection request is in place to control the input and output. On the client, after registering events that interest you (op_connect, op_read, and op_write combinations), The clientchlorophyll instance calls. connect
(Inetsocketaddress) connects to the server and then processes it accordingly. Note that the connection here is asynchronous, that is, it will return immediately and continue the subsequent executionCode.

Introduction to selector and selection key:

Selector is used to put events of interest to the channel into the queue, rather than submitting them to the application immediately, and wait for the registered channel to request to process these events by itself. In other words, the selector will report the prepared channel at any time in the FIFO order. So what is the selector reporting? Select key ). The key selection function is to indicate which channel is ready and what to prepare. You may think immediately that it must be an event of interest to the registered channel. Good. For example, for server-side Server Load balancer, you can call key. isacceptable () to notify the Server Load balancer of client connection requests. The corresponding functions include: selectionkey. isreadable (), selectionkey. iswritable (). Generally, poll events of interest in a loop (refer to the following code for details ). If there is no channel registered event in the selector, calling selector. Select () will be blocked until an event occurs. In addition, you can call selectnow () or select (long
Timeout ). The former returns immediately, and 0 is returned if there is no event; the latter returns after the timeout time. A selector can be registered with up to 63 channels at the same time.

 

Application instance:

The following is a list of client/server instance programs implemented using the asynchronous input/output mechanism. Program 1 (limited by space, only server implementation is provided. You can refer to the implementation of client code):

  1. Public class nblockingserver {
  2. Int Port = 8000;
  3. Int buffer size = 1024;
  4. Selector selector = NULL;
  5. Serversocketchannel serverchannel = NULL;
  6. Hashmap clientchannelmap = NULL; // used to store the socket and channel corresponding to each customer connection
  7. Public nblockingserver (INT port ){
  8. This. clientchannelmap = new hashmap ();
  9. This. Port = port;
  10. }
  11. Public void initialize () throws ioexception {
  12. // Initialize and instantiate a selector. A server can select a channel.
  13. This. selector = selector. open ();
  14. This. serverchannel = serversocketchannel. open ();
  15. This. serverchannel. configureblocking (false );
  16. Inetaddress localhost = inetaddress. getlocalhost ();
  17. Inetsocketaddress ISA = new inetsocketaddress (localhost, this. Port );
  18. This. serverchannel. socket (). BIND (ISA); // bind the socket to a port available on the server.
  19. }
  20. // Release resources at the end
  21. Public void finalize () throws ioexception {
  22. This. serverchannel. Close ();
  23. This. selector. Close ();
  24. }
  25. // Decodes the information that is read into the byte Buffer
  26. Public String decode (bytebuffer) throws
  27. Charactercodingexception {
  28. Charset = charset. forname ("ISO-8859-1 ");
  29. Charsetdecoder decoder = charset. newdecoder ();
  30. Charbuffer = decoder. Decode (bytebuffer );
  31. String result = charbuffer. tostring ();
  32. Return result;
  33. }
  34. // Listener port. Perform corresponding operations when the channel is ready
  35. Public void portlistening () throws ioexception, interruptedexception {
  36. // Register the op_accept event through the server Channel
  37. Selectionkey acceptkey = This. serverchannel. Register (this. selector,
  38. Selectionkey. op_accept );
  39. // When a registered event occurs, the return value of select () is greater than 0.
  40. While (acceptkey. selector (). Select ()> 0 ){
  41. System. Out. println ("event happened ");
  42. // Obtain all the available selection keys
  43. Set readykeys = This. selector. selectedkeys ();
  44. // Use the iterator to round the selection key
  45. Iterator I = readykeys. iterator ();
  46. While (I. hasnext ()){
  47. Selectionkey key = (selectionkey) I. Next ();
  48. I. Remove (); // Delete the selection key to be processed.
  49. If (key. isacceptable () {// If a client connection request exists
  50. System. Out. println ("more client connect in! ");
  51. Serversocketchannel nextready =
  52. (Serversocketchannel) Key. Channel ();
  53. // Obtain the client socket
  54. Socket S = nextready. Accept ();
  55. // Set the corresponding channel to asynchronous mode and register events of interest
  56. S. getchannel (). configureblocking (false );
  57. Selectionkey readwritekey =
  58. S. getchannel (). Register (this. selector,
  59. Selectionkey. op_read | selectionkey. op_write );
  60. // Associate the registered event with the socket
  61. Readwritekey. Attach (s );
  62. // Store the currently established client socket and corresponding channel in the hash table // clientchannelmap
  63. This. clientchannelmap. Put (s, new
  64. Clientchinstance (S. getchannel ()));
  65. }
  66. Else if (key. isreadable () {// if it is a channel read readiness event
  67. System. Out. println ("readable ");
  68. // Obtain the channel and socket corresponding to the selection key
  69. Selectablechannel nextready =
  70. (Selectablechannel) Key. Channel ();
  71. Socket socket = (socket) Key. Attachment ();
  72. // Process the event. The handling method is encapsulated in the clientchinstance class.
  73. This. readfromchannel (socket. getchannel (),
  74. (Clientchinstance)
  75. This. clientchannelmap. Get (socket ));
  76. }
  77. Else if (key. iswritable () {// if it is a channel write preparation event
  78. System. Out. println ("writeable ");
  79. // Obtain the socket post-processing method, same as above
  80. Socket socket = (socket) Key. Attachment ();
  81. Socketchannel channel = (socketchannel)
  82. Socket. getchannel ();
  83. This. writetochannel (Channel, "this is from server! ");
  84. }
  85. }
  86. }
  87. }
  88. // Write operations on the Channel
  89. Public void writetochannel (socketchannel channel, string message)
  90. Throws ioexception {
  91. Bytebuffer Buf = bytebuffer. Wrap (message. getbytes ());
  92. Int nbytes = channel. Write (BUF );
  93. }
  94. // Read operations on the Channel
  95. Public void readfromchannel (socketchannel channel, clientchinstance clientinstance)
  96. Throws ioexception, interruptedexception {
  97. Bytebuffer = bytebuffer. Allocate (buffersize );
  98. Int nbytes = channel. Read (bytebuffer );
  99. Bytebuffer. Flip ();
  100. String result = This. Decode (bytebuffer );
  101. // Close the channel when the client issues the "@ exit" command
  102. If (result. indexof ("@ exit")> = 0 ){
  103. Channel. Close ();
  104. }
  105. Else {
  106. Clientinstance. append (result. tostring ());
  107. // After reading a row, perform the corresponding operation
  108. If (result. indexof ("\ n")> = 0 ){
  109. System. Out. println ("client input" + result );
  110. Clientinstance.exe cute ();
  111. }
  112. }
  113. }
  114. // This class encapsulates how to perform operations on the client channel. The specific implementation can be done by reloading the execute () method.
  115. Public class clientchinstance {
  116. Socketchannel channel;
  117. Stringbuffer buffer = new stringbuffer ();
  118. Public clientchinstance (socketchannel channel ){
  119. This. Channel = channel;
  120. }
  121. Public void execute () throws ioexception {
  122. String message = "This Is response after reading from Channel! ";
  123. Writetochannel (this. Channel, message );
  124. Buffer = new stringbuffer ();
  125. }
  126. // When a row does not end, place the current word seek at the end of the buffer
  127. Public void append (string values ){
  128. Buffer. append (values );
  129. }
  130. }
  131. // Main program
  132. Public static void main (string [] ARGs ){
  133. Nblockingserver nbserver = new nblockingserver (8000 );
  134. Try {
  135. Nbserver. initialize ();
  136. } Catch (exception e ){
  137. E. printstacktrace ();
  138. System. Exit (-1 );
  139. }
  140. Try {
  141. Nbserver. portlistening ();
  142. }
  143. Catch (exception e ){
  144. E. printstacktrace ();
  145. }
  146. }
  147. }

 

Summary:

From the above section, we can see that the client has completed the customer/Server mode for multiple customers without introducing redundant threads. The callback mode is used in this program, which should be visible to the readers. Note that do not mix the original input/output package with the newly added input/output package. For some reason, these two packages are not compatible. When using channels, use buffering to control input and output. In Windows and j2se1.4, use Telnet.TestSuccessful.

The preceding code is transferred from http://space.itpub.net/17074730/viewspace-563262 .. This is really good ..

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.