logo
logo
Sign in

How to use callbacks in Java

avatar
Simba Institute
How to use callbacks in Java

In Java, a callback operation is a function that is provided to another function and run once a task is finished. The execution of a callback might happen synchronously or asynchronously. When a callback is synchronous, each function is run immediately after the previous one. An asynchronous callback executes a function after an arbitrary amount of time and without regard to the order in which other functions are called.

 

Beginning with the well-known illustration of the callback as a listener in the Observable design pattern, this article provides an introduction to callbacks in Java. You will see illustrations of numerous synchronous and asynchronous callback implementations, as well as one that makes use of CompletableFuture and is functional.

 

TABLE OF CONTENTS


  • Synchronous callbacks in Java
  • Anonymous inner class callback
  • Lambda callback
  • Asynchronous callbacks
  • Simple thread callback

Synchronous callbacks in Java

A synchronous callback function will always be run immediately following an action. It will therefore synchronise with the function carrying out the action.

 

Anonymous inner class callback

In Java, we use the idea of a callback function whenever we send an interface with a method implementation to another method. The Consumer functional interface and an unnamed inner class (implementation without a name) will be given in the following code to create the accept() method.
 
The action will be carried out from the performAction method once the accept() method has been developed, and the accept() method will then be carried out from the Consumer interface:
 
import java.util.function.Consumer;
 
public class AnonymousClassCallback {
 
  public static void main(String[] args) {
    performAction(new Consumer<String>() {
      @Override
      public void accept(String s) {
        System.out.println(s);
      }
    });
  }
 
  public static void performAction(Consumer<String> consumer) {
    System.out.println("Action is being performed...");
    consumer.accept("Callback is executed");
  }
 
}
The print statement is the result of this code:

 

Callback is carried out...

The Consumer interface was supplied to the performAction() method in this code, and after the action was complete, the accept() method was called.

Using an unnamed inner class is also extremely verbose, as you may have noticed. A lambda would be a far superior choice. Check out the results when we utilise a lambda for our callback function.

collect
0
avatar
Simba Institute
guide
Zupyak is the world’s largest content marketing community, with over 400 000 members and 3 million articles. Explore and get your content discovered.
Read more