Java Asynchronous Synchronous application

Source: Internet
Author: User
Java Asynchronous Synchronous application

Conceptual things always forget, write down, have time to look at the aftertaste

Java Asynchronous Synchronous application

The so-called asynchronous input and output mechanism, refers to the input and output processing, do not have to wait until the input and output processing completed before returning. So the asynchronous

Synonyms are non-blocking (None Blocking).


Online there are a lot of netizens use a very popular analogy to the synchronization and asynchronous explanation of the very thorough turn around


For example: Common B/S mode (synchronous) Ajax Technology (asynchronous)
Sync: Submitting requests-> waiting for server processing-> processing finished returning the client browser cannot do anything
Asynchronous: Request to trigger-> server processing via event (this is something that the browser can still do)-> processing complete


Synchronization is when you call me to dinner, I hear it and you go to dinner; If you don't hear it, you keep barking until I tell you to hear it.

, just to eat together.
Asynchronous is you call me, and then myself to eat, I get the news may go immediately, may also wait until after work to eat.
So, if I ask you to eat, use the synchronized method, you want to invite me to eat on the asynchronous method, so you can save money.

Take the example of communication
Sync: Sends a request, waits for return, and then sends the next request
Asynchronous: Sends a request, does not wait to return, can send the next request at any time
Concurrency: Sending multiple requests at the same time


Let's go back to the article on Java Asynchronous application

Writing a socket process communication program with an asynchronous input/output stream

The application interface package used to implement the asynchronous input/output mechanism was added to Merlin: Java.nio (the new input and output package, which defines the

Many basic type buffers (buffer), java.nio.channels (channels and selectors, etc., for asynchronous input and output),

Java.nio.charset (encoding and decoding of characters). The channel (Channel) first registers its own interest in the selector (Selector)

event, the selector notifies the registered channel by selecting the key (Selectionkey) when the corresponding event occurs. Then the channel will need

Processing of information, through buffer (buffer) packaging, coding/decoding, complete the input and output control.

Channel Introduction:

This is mainly about Serversocketchannel and socketchannel. They are all selectable (selectable) channels, which can be

Work in both synchronous and asynchronous ways (note that the option here is not to choose between two ways of working, but to have a choice

Registering events of interest to them). You can use Channel.configureblocking (Boolean) to set how it works. With Previous

Version of the API comparison, Serversocketchannel is equivalent to ServerSocket (Serversocketchannel encapsulates

ServerSocket), and Socketchannel is the equivalent of a socket (Socketchannel encapsulates a socket). When the channel is working in sync

Way, the programming method is similar to the previous, here mainly introduces the asynchronous work way.

The so-called asynchronous input and output mechanism, refers to the input and output processing, do not have to wait until the input and output processing completed before returning. So the asynchronous

Synonyms are non-blocking (None Blocking). On the server side, Serversocketchannel the static function open () to return a

Instance Serverchl. The channel then invokes Serverchl.socket (). bind () bound to a port on the server and calls the register (

Selector sel, selectionkey.op_accept) Register op_accept event into a selector (Serversocketchannel

Only Op_accept events can be registered. When a client requests a connection, the selector notifies the channel that there is a client connection request and can

The corresponding input and output control; On the client, the CLIENTCHL instance registers itself after an event of interest (can be

Op_connect,op_read,op_write), call Clientchl.connect (inetsocketaddress) Connect server

After the corresponding processing. Note that the connection here is asynchronous, that is, it returns immediately and continues to execute the following code.

Selector and selection key introduction:

The role of the selector (Selector) is to put events of interest into the queue instead of submitting them to the application immediately, etc.

The channels of the book themselves to request the handling of these events. In other words, the selector will be ready to report the channel as it is prepared, and it is

In the order of FIFO. So, what is the selector for reporting? Select the key (Selectionkey). The function of the Select key is

is to indicate which channel is ready and what is to be done. You may be thinking right away that it must be a registered channel that interests you.

Thing Yes, for example, for server-side Serverchl, you can call Key.isacceptable () to notify Serverchl that there are clients

Connection request. The corresponding functions are: selectionkey.isreadable (), selectionkey.iswritable (). In general, in

An event in a loop that polls for interest (refer to the code below). If the selector does not already have a channel registered event occurred, tune

Use Selector.select () to block until an event occurs. Alternatively, you can call Selectnow () or select (Long

Timeout). The former returns immediately and returns 0 when there is no event; the latter waits for timeout time to return. A selector can be at most

is registered with 63 channels.

application Example:

The following is a client/server instance program that is implemented with an asynchronous input/output mechanism D program Listing 1 (limited to space, only gives the server-side

Implementation, the reader can refer to the implementation of client-side code:

1.public class Nblockingserver {

2.int port = 8000;

3.int buffersize = 1024;

4.Selector Selector = null;

5.ServerSocketChannel serverchannel = null;

6.HashMap Clientchannelmap = null;//is used to store sockets and channels for each client connection

7.

8.public nblockingserver (int port) {

9.this.clientchannelmap = new HashMap ();

10.this.port = port;

11.}

12.

13.public void Initialize () throws IOException {

14.//initialization, instantiate a selector, a server-side selectable channel

15.this.selector = Selector.open ();

16.this.serverchannel = Serversocketchannel.open ();

17.this.serverchannel.configureblocking (FALSE);

18.InetAddress localhost = inetaddress.getlocalhost ();

19.InetSocketAddress isa = new inetsocketaddress (localhost, this.port);

20.this.serverchannel.socket (). bind (ISA);//Bind the socket to an available port on the server

21.}

Releasing resources at end of 22.//

23.public void Finalize () throws IOException {

24.this.serverchannel.close ();

25.this.selector.close ();

26.}

27.//reads the byte buffer to decode the information

28.public String decode (Bytebuffer Bytebuffer) throws

29.CharacterCodingException {

30.Charset Charset = Charset.forname ("iso-8859-1");

31.CharsetDecoder decoder = Charset.newdecoder ();

32.CharBuffer Charbuffer = Decoder.decode (Bytebuffer);

33.String result = Charbuffer.tostring ();

34.return result;

35.}

36.//listening ports, when the channel is ready to do the appropriate operation

37.public void Portlistening () throws IOException, Interruptedexception {

38.//server-side channel registration Op_accept Event

39.SelectionKey Acceptkey =this.serverchannel.register (This.selector,

40.selectionkey.op_accept);

41.//when a registered event occurs, the Select () return value is greater than 0

42.while (Acceptkey.selector (). Select () > 0) {

43.system.out.println ("event happened");

44.//get all the selected keys that are ready

45.Set Readykeys = This.selector.selectedKeys ();

46.//use iterators to poll selection keys

47.Iterator i = Readykeys.iterator ();

48.while (I.hasnext ()) {

49.SelectionKey key = (Selectionkey) i.next ();

50.i.remove ()//delete the selection key that will be processed currently

51.if (Key.isacceptable ()) {//If there is a client connection request

52.SYSTEM.OUT.PRINTLN ("More client connect in!");

53.ServerSocketChannel Nextready =

(Serversocketchannel) Key.channel ();

55.//Get client sockets

56.Socket s = nextready.accept ();

57.//sets the corresponding channel to asynchronous and registers the event of interest

58.s.getchannel (). Configureblocking (false);

59.SelectionKey Readwritekey =

60.s.getchannel (). Register (This.selector,

61.selectionkey.op_read| Selectionkey.op_write);

62.//the registered event with this socket

63.readwritekey.attach (s);

64.//the currently connected client sockets and corresponding channels in the hash table//clientchannelmap

65.this.clientchannelmap.put (S, new

66.ClientChInstance (S.getchannel ()));

67.}

68.else if (key.isreadable ()) {//If channel read ready event

69.SYSTEM.OUT.PRINTLN ("readable");

70.//obtain the channel and socket corresponding to the selection key

71.SelectableChannel Nextready =

(Selectablechannel) Key.channel ();

73.Socket socket = (socket) key.attachment ();

74.//handles the event, and the processing method is encapsulated in the class Clientchinstance

75.this.readfromchannel (Socket.getchannel (),

(clientchinstance)

77.this.clientchannelmap.get (socket));

78.}

79.else if (key.iswritable ()) {//If channel write ready event

80.system.out.println ("writeable");

81.//get socket after processing, method ditto

82.Socket socket = (socket) key.attachment ();

83.SocketChannel channel = (socketchannel)

84.socket.getchannel ();

85.this.writetochannel (channel, "This are from server!");

86.}

87.}

88.}

89.}

90.//writes to a channel

91.public void Writetochannel (Socketchannel channel, String message)

92.throws IOException {

93.ByteBuffer buf = Bytebuffer.wrap (Message.getbytes ());

94.int nbytes = Channel.write (BUF);

95.}

96.//read operations on channels

97.public void Readfromchannel (Socketchannel channel, Clientchinstance clientinstance)

98.throws IOException, Interruptedexception {

99.ByteBuffer Bytebuffer = bytebuffer.allocate (buffersize);

nbytes int = Channel.read (bytebuffer);

Bytebuffer.flip ();

102. String result = This.decode (Bytebuffer);

103.//When the client issues "Exit command, close its channel

(Result.indexof ("@exit") >= 0) {

Channel.close ();

106.}

. else {

108. Clientinstance.append (Result.tostring ());

109.//Read in line completed, perform the appropriate operation

Result.indexof ("" n ") >= 0) {

SYSTEM.OUT.PRINTLN ("Client input" +result);

112. Clientinstance.execute ();

113.}

114.}

115.}

116.//This class encapsulates how to operate on the client's channel, which can be implemented by overloading the Execute () method

117. public class Clientchinstance {

118. Socketchannel Channel;

119. StringBuffer buffer=new StringBuffer ();

Public clientchinstance (Socketchannel channel) {

121. This.channel = Channel;

122.}

123. public void execute () throws IOException {

124. String message = ' This are response after reading from channel! ';

Writetochannel (this.channel, message);

126. Buffer = new StringBuffer ();

127.}

128.///When the line is not finished, place the current word at the end of the buffer

129. public void Append (String values) {

130. Buffer.append (values);

131.}

132.}

133.

134.

135.//Main program

136. public static void Main (string[] args) {

137. Nblockingserver Nbserver = new Nblockingserver (8000);

138. try {

139. Nbserver.initialize ();

140.} catch (Exception e) {

E.printstacktrace ();

System.exit (-1);

143.}

144. Try {

145. nbserver.portlistening ();

146.}

147. catch (Exception e) {

148. E.printstacktrace ();

149.}

150.}

151.}

152.


Summary:

As can be seen from the above program section, the server side does not introduce redundant threads to complete the client/server model of multiple customers. Used in this program

The callback mode (CALLBACK), the attentive reader should have seen it already. Note that the original input-output package should not be used with the

The newly added input-output package is mixed, because for some reason, the two packages are incompatible. Use buffer to finish even when using channel

into the input and output control. The program was successfully windows2000,j2se1.4 under the Telnet test.

  Article citation: http://www.cnblogs.com/wanghf/archive/2009/05/20/1470631.html

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.