Implementing callback functions in Java

Event-driven programming forces us to use callback methods. Callback method is a method that is invoked when an event occurs. For example, our application is listening for broadcast messages. Upon reception of a message, a specific method must be called to process the message.

Callback mechanism in Java is supported with the use of interfaces. The interface declares the method that must be invoked.

First let's define a class that represents an event. We shall call it Event and it contains single member eventType which defines the type of event; whatever this means.

public class Event {

public int eventType = 0;


Define the interface that defines the method that must be invoked when event is received. In this example Event object is passed as argument to the method.

public interface ICallable {

public void processEvent(Event e);


Now we need a simple generator of events. In this example we will create a thread that will generate events at random intervals. Dummy variable eventType is also random integer.
Notice that we pass the reference to the ICallable interface in the constructor.

public class EventGenerator extends Thread {

private ICallable callable;

public EventGenerator(ICallable callable) {
this.callable = callable;

public void run() {

while (true) {

Event e = new Event();
e.eventType = (int) (5 * Math.random() + 1);


try {
sleep(((long) (10 * Math.random()) * 1000));
} catch (InterruptedException e1) {




In last step we need a class that implements the ICallable method. Every time when event occurs, the method processEvent will be called.
The most important step here is that we pass a reference of the object that implements the ICallable interface to the event generator.

public class Subscriber implements ICallable {

public void processEvent(Event e) {
System.out.println("New event occured: type=" + e.eventType);

public static void main(String[] args) {

// create new subscriber instance
Subscriber sub = new Subscriber();

// create event generator and pass the reference
// of subscriber, which implements callable interface
EventGenerator eg = new EventGenerator(sub);

// every time when event occurs, it will call
// processEvent() method in Subscriber