Asynchronous and Synchronous Callbacks in Java
Last Updated :
13 Aug, 2019
A CallBack Function is a function that is passed into another function as an argument and is expected to execute after some kind of event. The purpose of the callback function is to inform a class Sync/Async if some work in another class is done. This is very useful when working with Asynchronous tasks. Suppose we want to perform some routine tasks like perform some operation or display content after clicking a button, or fetching data from internet. This is also used in event handling, as we get notified when a button is clicked via callback function.
This type of design pattern is used in
Observer Design Pattern.The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependent, called observers, and notifies them automatically of any state changes, usually by calling one of their methods(
Source:wiki).
In Java, Callbacks can be implemented using an interface. The general procedure for implementation is given below.
1. Define the methods in an interface that we want to invoke after callback.
2. Define a class that will implement the callback methods of the interface.
3. Define a reference in other class to register the callback interface.
4. Use that reference to invoke the callback method.
Synchronous Callback
The code execution will block or wait for the event before continuing. Until your event returns a response, your program will not execute any further. So Basically, the callback performs all its work before returning to the call statement. The problem with synchronous callbacks are that they appear to lag.
Below is the simple implementation of this principle
Java
// Java program to illustrate synchronous callback
interface OnGeekEventListener {
// this can be any type of method
void onGeekEvent();
}
class B {
private OnGeekEventListener mListener; // listener field
// setting the listener
public void registerOnGeekEventListener(OnGeekEventListener mListener)
{
this.mListener = mListener;
}
// my synchronous task
public void doGeekStuff()
{
// perform any operation
System.out.println("Performing callback before synchronous Task");
// check if listener is registered.
if (this.mListener != null) {
// invoke the callback method of class A
mListener.onGeekEvent();
}
}
// Driver Function
public static void main(String[] args)
{
B obj = new B();
OnGeekEventListener mListener = new A();
obj.registerOnGeekEventListener(mListener);
obj.doGeekStuff();
}
}
class A implements OnGeekEventListener {
@Override
public void onGeekEvent()
{
System.out.println("Performing callback after synchronous Task");
// perform some routine operation
}
// some class A methods
}
Output:
Performing callback before synchronous Task
Performing callback after synchronous Task
Asynchronous Callback
An Asynchronous call does not block the program from the code execution. When the call returns from the event, the call returns back to the callback function. So in the context of Java, we have to Create a new thread and invoke the callback method inside that thread. The callback function may be invoked from a thread but is not a requirement. A Callback may also start a new thread, thus making themselves asynchronous.
Below is the simple implementation of this principle.
Java
// Java program to illustrate Asynchronous callback
interface OnGeekEventListener {
// this can be any type of method
void onGeekEvent();
}
class B {
private OnGeekEventListener mListener; // listener field
// setting the listener
public void registerOnGeekEventListener(OnGeekEventListener mListener)
{
this.mListener = mListener;
}
// My Asynchronous task
public void doGeekStuff()
{
// An Async task always executes in new thread
new Thread(new Runnable() {
public void run()
{
// perform any operation
System.out.println("Performing operation in Asynchronous Task");
// check if listener is registered.
if (mListener != null) {
// invoke the callback method of class A
mListener.onGeekEvent();
}
}
}).start();
}
// Driver Program
public static void main(String[] args)
{
B obj = new B();
OnGeekEventListener mListener = new A();
obj.registerOnGeekEventListener(mListener);
obj.doGeekStuff();
}
}
class A implements OnGeekEventListener {
@Override
public void onGeekEvent()
{
System.out.println("Performing callback after Asynchronous Task");
// perform some routine operation
}
// some class A methods
}
Output:
Performing operation in Asynchronous Task
Performing callback after Asynchronous Task
When To Use What
Synchronous Callback : Any process having multiple tasks where the tasks must be executed in sequence and doesn't occupy much time should use synchronous Callbacks.
For example : You're in a movie queue for ticket you can't get one until everyone in front of you gets one.
Asynchronous Callback : When the tasks are not dependent on each other and may take some time for execution we should use Asynchronous callbacks.
For example : When you order your food other people can also order their food in the restaurant. They don't have to wait for your order to finish, If you're downloading a song from internet, Getting an API response.
References:
https://www.javaworld.com/article/2077462/learn-java/java-tip-10--implement-callback-routines-in-java.html
https://en.wikipedia.org/wiki/Callback_(computer_programming)
Similar Reads
AsynchronousFileChannel in Java NIO
Java.nio package was introduced in the version java 1.4 edition. It allows us to deal with different channels concurrently because it supports concurrency and multi-threading. The asynchronous file channel API is responsible for the java NIO package and it is defined under the NIO channels package.
5 min read
Difference between synchronous and asynchronous requests in jQuery Ajax
In this article, we'll look at the differences between synchronous and asynchronous JQuery Ajax requests. JQuery provides several built-in methods for requesting data from the server: HTML, TXT, JSON, or String data can be requested. $.ajax() is a popular JQuery method for making synchronous and asy
6 min read
java.nio.channels.spi.AsynchronousChannelProvider Class in Java
Java programming offers a crucial component known as the java.nio.channels.spi.AsynchronousChannelProvider class, which plays an indispensable role in managing asynchronous I/O operations. This particular class is an integral part of the java.nio.channels package and serves as a provider for channel
3 min read
What is an asynchronous request in AJAX ?
In this article, we will have a deep look into Asynchronous AJAX requests. Basically, AJAX provides two types of requests namely Synchronous AJAX and Asynchronous AJAX. Asynchronous requests in AJAX don't wait for a response from the server whereas synchronous waits for the response. When asynchrono
3 min read
Promise vs Callback in JavaScript
In JavaScript, managing asynchronous operations is a key aspect of modern web development. Two popular approaches for handling these operations are Promises and Callbacks. While both techniques are designed to deal with tasks that take time to complete (like fetching data from a server), they work d
5 min read
Java Method and Block Synchronization
In Java, Synchronization is very important in concurrent programming when multiple threads need to access shared resources. Java Synchronization can be applied to methods and blocks. Method synchronization in Java locks the entire method and Block synchronization locks only a specific section of the
6 min read
java.net.CacheRequest Class in Java
CacheRequest class is used in java whenever there is a need for, storage of resources in ResponseCache. More precisely instances of this class provide an advantage for the OutputStream object to store resource data into the cache, in fact, This OutputStream object is invoked by protocol handlers. Ca
3 min read
Collections synchronizedSet() method in Java with Examples
The synchronizedSet() method of java.util.Collections class is used to return a synchronized (thread-safe) set backed by the specified set. In order to guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set. Syntax: public static <T>
2 min read
Collections synchronizedList() method in Java with Examples
The synchronizedList() method of java.util.Collections class is used to return a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list. Syntax: public static <
2 min read
Difference Between Callable and Runnable in Java
java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread â Subclass Thread and implement Runnable. There is no need of sub-classing Thread when a task can be done by overriding only run()
3 min read