开发者

could anybody please explain what is callback method with some sample example in java?

开发者 https://www.devze.com 2023-01-06 18:51 出处:网络
could anybody please explain what is callback method with some sample example in 开发者_Python百科java?Callback usually refers to an event-oriented approach whereby a listener is registered with a spe

could anybody please explain what is callback method with some sample example in 开发者_Python百科java?


Callback usually refers to an event-oriented approach whereby a listener is registered with a specific class and is called back whenever an event occurs. For example, the event could correspond to a user pressing a key or some data being received over TCP.

In the below example I've assumed the existence of a listener interface called EventListener. EventListeners are registered with an "observable" EventStream class (note that I've omitted the addListener and removeListener methods for clarity). Once started the event stream creates a separate thread that deals with the job of receiving events and calling back each listener. I've used a separate thread to illustrate that a callback method could be called by a thread other than the one used to register the listener.

public class EventStream {
  private final List<EventListener> listeners = new CopyOnWriteArrayList<EventListener>();

  public void start() {
    // Create thread responsible for performing I/O, creating and
    // broadcasting Event objects to any registered listeners.
    Thread t = new Thread(...);
    t.start();
  }

  // Notification method.  Called by internal event stream thread.
  protected void fireEventReceived(Event e) {
    for (EventListener l : listeners) {
      l.eventReceived(e);
    }
  }
}


I found this by googling "callback java":

http://www.javaworld.com/javaworld/javatips/jw-javatip10.html

If you start using google yourself, you could often get faster answers.


A callback or upcall is an invocation of a method in a higher layer that the caller. Particularly in procedural programming we typically think of higher layer calling into lower layers. Application code calling library code, and finer stratifications. A callback reverses the raltionship, by having a reference to the method passed to the lower layer.

In Java this is typically implemented by implementing an interface, as the language does not (yet) have a concept of a lone method reference - it's all objects with runtime classes. Often these will be implemented as anonymous inner classes. On the other hand it might be outer classes perhaps with some other configuration, such as servlets and applets.

The callback may be synchronous all asynchronous. Synchronous callbacks are called back during a single execution of a lower layer method, for instance as in the Execute Around Idiom. They may be called back later as in AWT/Swing events (same thread) or say java.util.concurrent.ExecutorService (different threads).

0

精彩评论

暂无评论...
验证码 换一张
取 消