Can someone explain what a callback method with an example example is in java?

Can someone explain what a callback method with an example example is in java?

+3
source share
3 answers

A callback usually refers to an event-oriented approach in which a listener registers in a particular class and returns back whenever an event occurs. For example, an event may correspond to the user by pressing a key or some data received via TCP.

EventListener. EventListener "" EventStream ( , addListener removeListener). , . , , , , .

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);
    }
  }
}
+3
+3

- , . , , . , , . , , .

Java , - . . , , , , .

The callback can be synchronous asynchronous. Synchronous callbacks are returned during one execution of a lower-level method, for example, as in Execute Around Idiom . They can be called later, as in AWT / Swing events (the same thread) or say java.util.concurrent.ExecutorService(different threads).

+2
source

Source: https://habr.com/ru/post/1753510/


All Articles