Java Asynchronous callbacks

Source: Internet
Author: User

Zen Building Moon ( Http://www.cnblogs.com/yaoyinglong )

1. Start telling the story:

Lunch time arrived, but the weather is too cold, do not want to go out of the office door, so you dialed the XXX restaurant reservation phone "Hello!" Hello, I am a side dish of xxx company, I point ... ". Then to continue to do your work, after a while, "Hello, xxx company's side dishes, your lunch arrived." This process is a typical asynchronous callback. So let's take a look at what the necessary conditions are in this:

    1. XXX Hotel must have the food delivery business;
    2. You must accept the meal, and if you don't accept the meal, you won't be eating.

The two agreements must be complied with, and one of them will not abide by it, and the work cannot be done.

First, we define a business agreement to deliver the meal:

1  Public Interface Sendfood {2     void Sendfood (Receivefood receive,string foodname); 3 }
View Code

then we define a protocol to where to send the meal:

1  Public Interface Receivefood {2     void Receivefood ( Food and food); 3 }
View Code

then we define a restaurant where he complies with the delivery protocol:

1  Public classXxxrestaurantImplementsSendfood {2 3 @Override4      Public voidSendfood (Receivefood receive,string foodname) {5         //tell the kitchen to cook ...6Food lunch=Cook (foodname);7         //Take the lunch to the place you agreed to.8 Receive.receivefood (lunch);9     }Ten     PrivateFood Cook (String foodname) { One         //after some time, some of the food has been wrong. AFood somefood=NewFood (foodname);  -         returnSomefood; -     } the}
View Code

then we define ourselves, and we abide by the agreement to accept the meal:

1  Public classXiaocaiImplementsReceivefood {2     PrivateSendfood Restaurant;3      PublicXiaocai (Sendfood restaurant) {4          This. restaurant=Restaurant;5     }6      Public voidOrderfood (FinalString Foodname) {7         NewRunnable () {8 @Override9              Public voidrun () {TenRestaurant.sendfood (Xiaocai. This, foodname); One             } A }.run (); -     } - @Override the      Public voidReceivefood (food food) { -System.out.println ("Good Food"); -     } -}
View Code

Test it:

2. Understanding

Therefore, we can understand the callback as follows: a delegate B to do one thing, then B and then notify A. Behave in code that is: Method of Class A FA calls the method of Class B fb, after the meal FB called the method of Class A fa1.

3. The difference between multi-threading and Asynchrony [reprint]

First thank you very much YDHL iPhone Dev 's contribution

3.1 Nature of asynchronous operations

All programs will eventually be executed by the computer hardware, so in order to better understand the nature of the asynchronous operation, we need to understand its hardware base. Familiar with the computer hardware friend is certainly not unfamiliar with the word DMA, hard disk, optical drive technical specifications have a clear DMA mode indicator, in fact, the network card, sound card, video card also has DMA function. DMA is the meaning of direct memory access, which means that the DMA-capable hardware does not consume CPU resources when exchanging data with the memory. As long as the CPU sends an instruction when it initiates the data transfer, the hardware begins to exchange data between itself and the memory, and after the transfer is complete, the hardware triggers an interrupt to notify the operation to complete. These I/O operations that do not consume CPU time are the hardware basis for asynchronous operations. Therefore, even in a single process such as DOS (and the Wireless Path concept) system can also initiate asynchronous DMA operation.

3.2 The nature of threads

A thread is not a function of a computer's hardware, but rather a logical function provided by the operating system, which is essentially a piece of code that runs concurrently in a process, so the thread requires the operating system to run and dispatch the CPU resources.

3.3 Advantages and disadvantages of asynchronous operations

Because asynchronous operations do not require additional thread burdens and are handled in a callback manner, the processing function can eliminate the possibility of deadlocks by eliminating the need for shared variables (even if it is not completely unused, at least by reducing the number of shared variables). Of course, asynchronous operations are not flawless. Writing asynchronous operations is a high degree of complexity, the program mainly uses callback method to handle, and ordinary people's way of thinking some first, and difficult to debug.

3.4 Advantages and disadvantages of multi-threading

The advantages of multithreading are obvious, the handlers in the thread are still sequential execution, in line with the normal thinking habits, so programming is simple. However, the disadvantage of multithreading is equally obvious, the use of threads (misuse) will bring the burden of context switching to the system. Also, shared variables between threads can cause deadlocks to occur.

3.5 Scope of application

After understanding the pros and cons of threading and asynchronous operations, we can explore the logical use of a thread and async. I think that when I am required to perform I/O operations, it is more appropriate to use asynchronous operations than to use thread + synchronous I/O operations. I/O operations include not only direct files, read and write to the network, but also database operations, Web Service, HttpRequest, and cross-process calls such as. Net Remoting.
The scope of the thread is the kind that requires long CPU operations, such as long-time graphics processing and algorithm execution. But often because of the simple and consistent use of threading programming, many friends tend to use threads to perform long-time I/O operations. This is harmless when there are only a few concurrent operations, which is not appropriate if you need to handle a large number of concurrent operations.

Java Asynchronous callbacks

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.