Follow treslines by email clicking Here!

Saturday, October 13, 2012

Understanding Callbacks with Java - Inversion of control

Callback Pattern in Java Environment


Hi there! today i wanna share something with you, that it is very common and widely used in javascript for example. I'm speaking of callbacks. Do you know how and when this "pattern" is used? Do you really understand it in a java context (environment)? Well i was asking me also some of those questions and that's the reason i started to learn more about it. The ideia behind it is the inversion of control (abbreviated IoC). This paradigma describes the way frameworks work. It is also known as the "Hollywood principle - Don't call me, we will call you"

Simplified Callback pattern in Java just to understand it. Concrete example follows bellow.




interface CallBack {
    void methodToCallBack();
}

class CallBackImpl implements CallBack {
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();
        caller.register(callBack);
    }
} 

Ok you may be asking you, when this usefull or may be asking you what's the difference between calling directly callback.methodToCallBack() right?

ANSWER: well, this example just shows to you how to construct such a callBack function when working in a java environment. Certainlly it doesn't make it any sense to use it that way. Let's get a little deeper into a concrete useful example now.

The idea behind it is the "INVERSION OF CONTROL". Let's take a timer as a realistic example. Let's supose that you know, that a specific timer supports callback functions every hour. Exactly it means, that every hour, the timer will call your registed call method function.

Conctrete Example:

Let's say we wanna update the time of a website every hour. Here is the UML of the following example:


Callback Interface

Let's define first the callback interface:


import java.util.ArrayList;
import java.util.List;

// For example: Let's assume that this interface is offered from your OS to be implemented
interface TimeUpdaterCallBack {
    void updateTime(long time);
}

// this is your implementation.
// for example: You want to update your website time every hour
class WebSiteTimeUpdaterCallBack implements TimeUpdaterCallBack {

    @Override
    public void updateTime(long time) {
        // print the updated time anywhere in your website's example
        System.out.println(time);
    }
}

The SystemTimer that supports Callback functions in our example:



// This is the SystemTimer implemented by your Operating System (OS)
// You don't know how this timer was implemented. This example just
// show to you how it could looks like. How you could implement a
// callback by yourself if you want to.
class SystemTimer {

    List<TimeUpdaterCallBack> callbacks = new ArrayList<TimeUpdaterCallBack>();

    public void registerCallBackForUpdatesEveryHour(TimeUpdaterCallBack timerCallBack) {
        callbacks.add(timerCallBack);
    }

    // ... This SystemTimer may have more logic here we don't know ...

    // At some point of the implementaion of this SystemTimer (you don't know)
    // this method will be called and every registered timerCallBack
    // will be called. Every registered timerCallBack may have a totally
    // different implementation of the method updateTime() and my be
    // used in different ways by different clients.
    public void oneHourHasBeenExprired() {

        for (TimeUpdaterCallBack timerCallBack : callbacks) {
            timerCallBack.updateTime(System.currentTimeMillis());
        }
    }
}

And finally our WebSiteTimeUpdater which is our client in this fictive and simple example:



// This is our client. It will be used in our WebSite example. It shall update
// the website's time every hour.
class WebSiteTimeUpdater {

    public static void main(String[] args) {
        SystemTimer SystemTimer = new SystemTimer();
        TimeUpdaterCallBack webSiteCallBackUpdater = new WebSiteTimeUpdaterCallBack();
        SystemTimer.registerCallBackForUpdatesEveryHour(webSiteCallBackUpdater);
    }
}

Advertising:
Optimized bets for playing EuroMillion's lottery on your Mobile Phone! 



9 comments:

  1. What is the theme you are using in eclipse?
    Would you please send the name or, preferably, the .epf file? I like the blue tone :)

    ReplyDelete
    Replies
    1. Hi! i like it too and i'm trying to create something similar to that in eclipse. I'm using sublime text. as soon as i have something like that, i'll be sending to you ok.

      regards,
      Ricardo

      Delete
    2. It is Sublime 2 or 3 its free to use or you can buy a license.

      Delete
  2. That doesn't seems like eclipse - that's probably QT.

    ReplyDelete
    Replies
    1. Did anybody say vim?

      Delete
    2. It seems like IntelliJ IDEA http://www.jetbrains.com/idea/

      Delete
  3. I'm not understanding how your example this is anymore concrete than the original example you pasted that appears everywhere else on the internet.

    ReplyDelete
  4. Great post :). We could also call the callback like this:

    caller.register(new Callback() {
    @Override
    public void methodToCallback() {
    // Show a message
    }
    });

    Thanks,

    ReplyDelete
  5. Great post, thank you!
    Then, you could say, for a newbie, that a callback is a kind of listener for OS calls?

    ReplyDelete