What is a call back interface in Java?

java

Solution

A general requirement for an interface to be a "callback interface" is that the interface provides a way for the callee to invoke the code inside the caller. The main idea is that the caller has a piece of code that needs to be executed when something happens in the code of another component. Callback interfaces provide a way to pass this code to the component being called: the caller implements an interface, and the callee invokes one of its methods.

The callback mechanism may be implemented differently in different languages: C# has delegates and events in addition to callback interfaces, C has functions that can be passed by pointer, Objective C has delegate protocols, and so on. But the main idea is always the same: the caller passes a piece of code to be called upon occurrence of a certain event.

Problem

This code snippet for the interface SetObserver is taken from Effective Java (Avoid Excessive Synchronization Item 67) ``` public interface SetObserver<E> { // Invoked when an element is added to the observable set void added(ObservableSet<E> set, E element); } ``` And the `SetObserver` is passed to `addObserver()` and `removeObserver` method as given below : ``` // Broken - invokes alien method from synchronized block! public class ObservableSet<E> extends ForwardingSet<E> { public ObservableSet(Set<E> set) { super(set); } private final List<SetObserver<E>> observers = new ArrayList<SetObserver<E>>(); public void addObserver(SetObserver<E> observer) { synchronized (observers) { observers.add(observer); } } public boolean removeObserver(SetObserver<E> observer) { synchronized (observers) { return observers.remove(observer); } } private void notifyElementAdded(E element) { synchronized (observers) { for (SetObserver<E> observer : observers) observer.added(this, element); } } ``` Bloch refers to the `SetObserver<E>` interface as a call back interface . When is a interface called an call back interface in Java?

Original source

Related problems