I'm a programming noob and didn't quite understand the concept behind callback methods. Tried reading about it in wiki and it went over my head. Can somebody please explain this in simple terms?
A callback method in java is a method that gets called when an event (call it E ) occurs. Usually you can implement that by passing an implementation of a certain interface to the system that is responsible for triggering the event E (see example 1).
There are two types of callbacks, differing in how they control data flow at runtime: blocking callbacks (also known as synchronous callbacks or just callbacks) and deferred callbacks (also known as asynchronous callbacks).
We want to log a message to the console but it should be there after 3 seconds. In other words, the message function is being called after something happened (after 3 seconds passed for this example), but not before. So the message function is an example of a callback function.
The callback is something that you pass to a function, which tells it what it should call at some point in its operation. The code in the function decides when to call the function (and what arguments to pass). Typically, the way you do this is to pass the function itself as the 'callback', in languages where functions are objects. In other languages, you might have to pass some kind of special thing called a "function pointer" (or similar); or you might have to pass the name of the function (which then gets looked up at runtime).
A trivial example, in Python:
void call_something_three_times(what_to_call, what_to_pass_it): for i in xrange(3): what_to_call(what_to_pass_it) # Write "Hi mom" three times, using a callback. call_something_three_times(sys.stdout.write, "Hi mom\n")
This example let us separate the task of repeating a function call, from the task of actually calling the function. That's not very useful, but it demonstrates the concept.
In the real world, callbacks are used a lot for things like threading libraries, where you call some thread-creation function with a callback that describes the work that the thread will do. The thread-creation function does the necessary work to set up a thread, and then arranges for the callback function to be called by the new thread.
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