views:

820

answers:

5

In a previous SO question it was recommended to me to use callback/event firing instead of polling. Can someone explain this in a little more detail, perhaps with references to online tutorials that show how this can be done for Java based web apps.

Thanks.

+1  A: 

Callback is when you pass a function/object to be called/notified when something it cares about happens. This is used a lot in UI - A function is passed to a button that is called whenever the button is pressed, for example.

Nathaniel Flath
A: 

There are two players involved in this scenario. First you have the "observed" which from time to time does things in which other players are interested. These other players are called "observers". The "observed" could be a timer, the "observers" could be tasks, interested in alarm events.

This "pattern" is described in the book "Design Patterns, Elements of Reusable Object-Oriented Software" by Gamma, Helm, Johnson and Vlissides.

Two examples:

  1. The SAX parser to parse XML walks trough an XML file and raises events each time an element is encountered. A listener can listen to these elements and do something with it.
  2. Swing and AWT are based on this pattern. When the user moves the mouse, clicks or types something on the keyboard, these actions are converted into events. The UI components listen to these

events and react to them.

Bruno Ranschaert
+2  A: 

The difference between polling and callback/event is simple:

  • Polling: You are asking, continuously or every fixed amount of time, if some condition is meet, for example, if some keyboard key have been pressed.
  • Callback: You say to some driver, other code or whatever: When something happens (the keyboard have been pressed in our example), call this function, and you pass it what function you want to be called when the event happens. This way, you can "forget" about that event, knowing that it will be handled correctly when it happens.
Artur Soler
A: 

Being notified via an event is almost always preferable to polling, especially if hardware is involved and that event originates from a driver issuing a CPU interrupt. In that case, you're not using ANY cpu at all while you wait for some piece of hardware to complete a task.

dicroce
+4  A: 

The definition of a callback from Wikipedia is:

In computer programming, a callback is executable code that is passed as an argument to other code. It allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.

In it's very basic form a callback could be used like this (pseudocode):

void function Foo()
{
   MessageBox.Show("Operation Complete");
}

void function Bar(Method myCallback)
{
  //Perform some operation
  //When completed execute the callback method
  myCallBack().Invoke();
}

static int Main()
{
   Bar(Foo); //Pops a message box when Bar is completed
}

Modern languages like Java and c# have a standardized way of doing this and they call it events. An event is simply a special type of property added to a class that contains a list of Delegates / Method Pointers / Callbacks (all three of these things are the same thing. When the event gets "fired" it simply iterates through it's list of callbacks and executes them. These are also referred to as listeners.

Here's an example

public class Button
{
   public event Clicked;

   void override OnMouseUp()
   {
        //User has clicked on the button. Let's notify anyone listening to this event.
       Clicked(); //Iterates through all the callbacks in it's list and calls Invoke();
   }
}

public class MyForm
{
   private _Button;

   public Constructor()
   {
       _Button = new Button();

      //Different languages provide different ways of registering listeners to events.
      // _Button.Clicked += Button_Clicked_Handler;
      // _Button.Clicked.AddListener(Button_Clicked_Handler); 
   }

   public void Button_Clicked_Handler()
   {
       MessageBox.Show("Button Was Clicked");
   }
}

In this example the Button class has an event called Clicked. It allows anyone who wants to be notified when is clicked to register a callback method. In this case the "Button_Clicked_Handler" method would be executed by Clicked event.

Eventing/Callback architecture is very handy whenever you need to be notified that something has occurred elsewhere in the program and you have no direct knowledge of when or how this happens.

This greatly simplifies notification. Polling makes it much more difficult because you are responsible for checking every so often whether or not an operation has completed. A simple polling mechanism would be like this:

static void CheckIfDone()
{
    while(!Button.IsClicked)
    {
       //Sleep
    }

    //Button has been clicked.
}

The problem is that this particular situation would block your existing thread and have to continue checking until Button.IsClicked is true. The nice thing about eventing architecture is that it is asynchronous and let's the Acting Item (button) notify the listener when it is completed instead of the listener having to keep checking,

Micah