CallBack Pattern

 


* Pattern Properties

* Applicability

* Description

* Implementation

* Benefits and drawbacks

* Pattern Changes

* Related patterns

* Bibliography

Exhibition on “Pattern CallBack”

(Recall)

Pattern properties

Type: Processing (behavioral)

Level Architecture

Purpose

Allow a client to log into a server for certain operations. Thus, the server can notify the client when the operation is complete.

Introduction

A personal information manager distributed periodically conduct costly requests to a server. For example, the time needed to recover an entire project stored on a server is quite unpredictable the project could have thousands of tasks and developments.

In this situation, the fact of keeping open a network connection would be a constraint on the server. Although keeping the connection open may improve server efficiency, having a connection for each client severely limits the number of client requests that the server can process concurrently.

Instead of that client and server stay connected, it would be better to allow the server to connect to the client when complete its corresponding request. The pattern CallBack uses this approach.

* The client sends a request to retrieve a server project, providing the necessary information to the callback with the request.

* The client is disconnected from the server and allows it to take the time needed to recover the project.

* When the server completes the task, the client connects and sends information of the requested project.

Among the advantages gained by the use of this pattern include saving bandwidth and more efficient use of processing time on the server. This solution also gives freedom wing server performing actions such as queue the requests and use priority tasks to manage more efficiently the resources available at all times.

Applicability

Use the callback pattern for a client / server system in which customers engage in costly operations, and when one of the following two rules is true:

* You want to keep server resources for active communication.

* The customer can and must continue until the information becomes available. This can be achieved simply by having the client is multithreaded.

Description

In some distributed systems, a server must spend a lot of processing time to meet the requests of customers. In such systems, synchronous communication probably not the best option if the server maintains contact with the client during the process, using resources that could be applied to other tasks such as communicating with other clients.

Imagine a system where the user wants to run a complex query on a table in a moderately large database, such as a table with information about customers with more than 10,000 records. In a client / server synchronous, the client process would have to wait, possibly for a long period of time, until the server ended. The server would execute the request, and will manage all possible steps to organize, format and package the data, until he finally could return customer data.

The alternative is to create a system that allows a client to register with the server to receive notifications. When the server completes the operation requested, sends a notification to the customer. At the time until the operation completes, the client and the server are free to use their resources for productive purposes than maintaining the communication link specific.

The callback pattern provides this capability, allowing client / server communication asynchronous. The process involves three main steps:

* For example, the client contacts the server and make a request. Typically, the client requests information such as sales statistics for 2001, or an action such as entering the user in the tour. Because the client does not expect an immediate response, provides the necessary information for the server to contact him.

* Record client: the client makes a request, providing contact information server.

* Processing on the server: the server processes the request and formats a response if necessary. During that time, the client can perform other tasks, or the server can communicate with other clients. * The information requested by the client. This approach is generally used when the client nenecita all data sent or when the data takes up relatively little bandwidth.

* A message informing the customer that the data or some data are available. This option is generally used when there is a lot of information so that the customer can choose to recover a portion of the data once they become available, or only the data you need from all the demand.

Such as Callback pattern, consider a father and his three sons that they go shopping. The son # 1 wants a Laser Robot, the number 2 son wants a laptop and son number 3 on the last book published by Prentice Hall Java. However:

* Find all of these things can take a long time, especially not sold in the same trade.

* The children are only able to pay attention for five minutes and go crazy if they have to be shopping for a long time.

* The father can only buy one or two things at once if you buy more, their performance would fall.

Fortunately, the parent can leave their children in the games room, or let them fight each other, or anything else that comes to mind. Then the father can go to buy one item, leave it again, go buy another and so on.

You can use the callback pattern in many applications:

* Software agents, now very popular on the Web, you can use callbacks to notify the client that the request has been completed. For example, imagine an agent job search on Monster.com. A user can enter search criteria for the job you want to get, for example could be looking for one that is asked a good nose for making beer taster. Subsequently, the server notifies the user when there is a position available in a beer taster.

* Applications that require costly operations databases, such as data mining, pattern CallBack often used to increase the number of customers we offer a service effectively.

* CallBack pattern can be used in applications that have detailed workflow on the server. For example, a server used for processing orders, often runs a series of operations once a customer has placed the order. The server usually check inventory, validate payment and distribution information, and coordinates with other information systems, billing and order fulfillment. CallBack pattern allows the server to notify customers on order status after performing the above steps. How are you operations can take hours or days, customers also prefer this style solution.

 

* Callback Server: when the server completes the request, sends a notification message. The notice usually takes one of two ways:p align = “center”>

Implementation:

The diagram shows the components of the pattern CallBack

In the figure of the diagram shows the pattern sequence CallBack

This pattern requires some basic requirements on the client and server:

* Customer: the customer must provide retornollamada interface for the server, so that it can contact the customer when the request is completed.

* Server: beyond traditional customer interface, the server needs some way to tell customers when it has finished processing. In addition, the server must be capable of processing and possibly storing the customer’s requests.

Advantages and drawbacks:

The biggest advantage of the Callback pattern is to improve the efficiency of the system especially in the server performance. Most improvements can be seen in two distinct areas:

* Processing on the server: the server has to maintain communication threads to serve customers, so you can channel these resources to processing requests from clients or serve callers. In addition, the server can perform processing when it sees fit, not have to be the moment it receives the request.

* Communication Server: The server does not have to keep an open connection while the client waits for the results. This means that a server can support a greater number of callers with a limited communication resources, such as would occur with the sockets (sockets).

That is precisely the main motivation for using the CallBack pattern in the systems. In the most extreme cases, can mean the difference between having a group of servers in parallel and use a machine to handle requests from clients.

Another advantage is that the client does not have to wait for the processing of the server and can continue with other tasks. The client can continue what he was doing while waiting for server response. When the result is available, it can be shown immediately.

Depending on the implementation of the pattern, the client requests can be queued, allowing the server to organize and prioritize their workload. It also allows the server to notify clients when changes occur over time is the ordinary life of a client. Web agents are a good example of this, because they allow customers to put a request in a Web session and receive a notification from another session.

A challenge Callback pattern is that a client needs the server listen for callbacks. This often makes the client code is more complete, and increases the load on client systems. An additional problem arises from the fact that decouples Callback request. That tends to inhibit the cancellation or amendment of a petition once it has been sent to the server.

Pattern Variations:

The Callback pattern variations are generally focused on the server processing strategies and approaches on notifications to customers. The two main approaches to processing on the server side are:

* Straight-Through Processing: With this approach, the server creates a worker thread to meet the requests of customers. Implementation is simple, but it can be difficult to scale to a large number of service requests.

* Queue patterns: the server maintains a queue with requests from customers and a pool of worker threads. The worker threads are assigned to execute the processing of customers continuously.

Only options are available for service of customers, depending on the application requirements:

* Callback active, a client uses a process similar to a server to listen for incoming connections. This allows customers to receive direct notification from the server.

* Survey of client: the client needs to periodically review the status of your request. When the petition, or a portion thereof is completed, the customer requests the information for the server.

* Explicit recognition: a server can retransmit a message until it receives confirmation from the customer. This approach is typically used when processing on the server can last much longer than the lifetime of the customer. Although this is not relevant because TCP sockets not remain open unless the customer is present to do their job, if it is significant when used on communication technologies unreliable UDP.

Related patterns:

Among the patterns related to Callback include Worker Thread. Thread worker pattern is used to help plan customer calls.

The requests are placed in a queue, and workers process threads.

Example:

CallbackServer.java

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface extends Remote {CallbackServer

public String getProject (String project, String callbackMachine,

CallbackObjectName String) throws RemoteException;

}

CallbackServerImpl.java

java.rmi.Naming import;

java.rmi.server.UnicastRemoteObject import;

public class implements CallbackServerImpl CallbackServer {

private static final String CALLBACK_SERVER_SERVICE_NAME = “callbackServer”

CallbackServerImpl public () {

try {

UnicastRemoteObject.exportObject (this);

Naming.rebind (CALLBACK_SERVER_SERVICE_NAME, this);

}

catch (Exception exc) {

System.err.println (“Error using RMI to register the CallbackServerImpl” + exc);

}

}

public String getProject (String project, String callbackMachine,

CallbackObjectName String) {

CallbackServerDelegate new (project, callbackMachine, callbackObjectName)

}

}

CallbackServerDelegate.java

import java.net.MalformedURLException;

java.rmi.Naming import;

java.rmi.NotBoundException import;

import java.rmi.RemoteException;

public class implements Runnable {CallbackServerDelegate

Thread processingThread private;

private String project;

private String callbackMachine;

private String callbackObjectName;

public CallbackServerDelegate (NewProject String, String newCallbackMachine,

NewCallbackObjectName String) {

Project = NewProject;

callbackMachine = newCallbackMachine;

callbackObjectName = newCallbackObjectName;

processingThread = new Thread (this);

processingThread.start ();

}

public void Run () {

Project result = getProject ();

sendProjectToClient (result);

}

private Project getProject () {

return new Project (project, “Test project”);

}

private void sendProjectToClient (Project project) {

try {

String url = “/ /” + callbackMachine + “/” + callbackObjectName;

RemoteClient = Naming.lookup Object (url);

if (instanceof remoteClient CallbackClient) {

((CallbackClient) remoteClient). ReceiveProject (project);

}

}

catch (RemoteException exc) {}

catch (NotBoundException exc) {}

catch (MalformedURLException exc) {}

}

}

CallbackClient.java

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface extends Remote {CallbackClient

public void receiveProject (Project project) throws RemoteException;

}

CallbackClientImpl.java

java.net.InetAddress import;

import java.net.MalformedURLException;

import java.net.UnknownHostException;

java.rmi.Naming import;

java.rmi.server.UnicastRemoteObject import;

java.rmi.NotBoundException import;

import java.rmi.RemoteException;

public class implements CallbackClientImpl CallbackClient {

private static final String CALLBACK_CLIENT_SERVICE_NAME = “callbackClient”

private static final String CALLBACK_SERVER_SERVICE_NAME = “callbackServer”

private static final String CALLBACK_SERVER_MACHINE_NAME = “localhost”;

Project requestedProject private;

projectAvailable private boolean;

CallbackClientImpl public () {

try {

UnicastRemoteObject.exportObject (this);

Naming.rebind (CALLBACK_CLIENT_SERVICE_NAME, this);

}

catch (Exception exc) {

System.err.println (“Error using RMI to register the CallbackClientImpl” + exc)

}

}

public void receiveProject (Project project) {

requestedProject = project;

projectAvailable = true;

}

public void requestProject (String ProjectName) {

try {

String url = “/ /” + CALLBACK_SERVER_MACHINE_NAME + “/” + CALLBACK_SERVER_SERVICE_NAME;

RemoteServer = Naming.lookup Object (url);

if (instanceof remoteServer CallbackServer) {

((CallbackServer) remoteServer). GetProject (ProjectName,

InetAddress.getLocalHost (). Gethostname (),

CALLBACK_CLIENT_SERVICE_NAME)

}

projectAvailable = false;

}

catch (RemoteException exc) {}

catch (NotBoundException exc) {}

catch (MalformedURLException exc) {}

catch (UnknownHostException exc) {}

}

public Project getProject () {return requestedProject;}

public boolean isProjectAvailable () {return projectAvailable;}

}

Bibliography:

Design patterns applied to JAVA

STEPHEN STELTING / OLAV MAASS

 

Darwin Vargas Velez

Equator Technological University

Advanced Programming Techniques

2006/06/30

The 6th “A” Computer




Recent Articles


Essential nutrients

WATER Essential component for life and abundant in most foods. The water is absorbed in the intestine and then transported by the blood to other organs. Can be found in the body as part of intracellular protoplasm and extracellular, and interstitial fluid, lymph, and as part of blood plasma. FUNCTIONS * Transportation of nutrients and waste products * Regulation of body temperature * Solvent substances * Structural component of cells The water is eliminated through urine, feces, skin and lungs. The balance between loss and gain of water should be neutral because a positive balance of ending a picture of water retention and negative a picture of dehydration. DAILY NEEDS …


Importance of agro-export sector in the Peruvian economy

* Agriculture sector * Problems such Peruvian agriculture. Environmental conservation erosion and salinization * Minifundio * Prices and markets * Technical Support * Agricultural Credit * Food Security * Employment * Health * Laws that promote agricultural export * Conditions favorable base * Classification of major agricultural products * Industry Structure * Sensitivity analysis AGRICULTURAL SECTOR The agricultural sector plays an important role in the country’s economic activity. Your participation on GDP is around 7% and its evolution has been over the last decade than the national average even though it has had to face the ravages of nature like floods and El Ni~no that dealt two blows to the …


VIEW OF LIFE FROM GLOBALISATION

  Index- 1. Introduction 2. The contemporary context: GLOBALIZATION 3. Know thyself: REFLECTIONS 4. Life Vision 5. Bibliography 1. Introduction Actually I have no specific recipes for carrying so many people who excel need to focus a vision of life. I would like to be “pervasive” to be everywhere: feel the need of the other, guide, chat, suffering, increase their self-esteem to show a projection of real life and daring. Times have changed from a simple life at a competitive and complex life. Imposed on us to be better every day. Action project with excellence, efficiency and effectiveness in pursuit of priorities to excel. That’s why we were motivated to …


Rice Production

Abstract * Origins of Rice * Nutritional Value * Rice in Peru * Basic features of rice producers * Rice production chain * Cultivation and harvesting of rice * Rice and the economy * The rice in the world * World price of rice * Production in Peru * Producer price * Consumer prices * Conclusions * Bibliography ABSTRACT This monograph is the rice production both globally and nationally, clearly placing greater emphasis on our Peruvian market. It has the nutritional value of rice, the departments that produce the traits of producers, farming methods, the change that has had this product not only in price but in production both globally …