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?
Interfaces can be used to implement callbacks in Java. A callback is a situation where you'd like to pass a reference to some behavior and have another object invoke it later. In C or C++, this is prime territory for function pointers. In Java, we use interfaces instead.
An application implements a CallbackHandler and passes it to underlying security services so that they may interact with the application to retrieve specific authentication data, such as usernames and passwords, or to display certain information, such as error and warning messages.
Definition. Callback methods are those methods which are used by container during the lifecycle of an instance to manage it. Callback methods are invoked by container after instance is instantiated and before instance is destroyed. Types. Spring has two callbacks- initialization and destruction.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With