Monday, March 13, 2023

Callback in Java

 



In this post we will review an example of callback in Java. Callbacks enables us to handle task asynchronously. For example, we can run a long execution time query and instead of waiting for the query result to return, we can do something else meanwhile. Asynchronous and callbacks are extensively used in GUI applications, where in most cases a single thread is updating the GUI, and we don't want any long running task to make the GUI freeze. Hence any background long processing is done using asynchronous callbacks.


Lets examine an example: we have query API that runs a query for 1 second, and supplies a callback API.


class QueryApi implements Runnable {
private final String queryText;
private final ApiCallback callback;

QueryApi(String queryText, ApiCallback callback) {
this.queryText = queryText;
this.callback = callback;
}

public void runQuery() {
new Thread(this).start();
}

public void run() {
System.out.println("processing the query");
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {

}

if (new Random().nextBoolean()) {
this.callback.onSuccess("query " + this.queryText + " result: very good");
} else {
this.callback.onFailure("bad luck");
}
}
}



The callback is an interface with success and failure handling:


interface ApiCallback {
void onSuccess(String queryResult);

void onFailure(String errorMessage);
}


To use the API, we implement the callbacks, and call the query API:


public class Main implements ApiCallback {
public static void main(String[] args) throws Exception {
new Main().doWork();
}

private void doWork() {
QueryApi api = new QueryApi("get all data", this);
api.runQuery();
System.out.println("i am not waiting for the query, so I can do other tasks");
}

@Override
public void onSuccess(String queryResult) {
System.out.println("YES!\n" + queryResult);
}

@Override
public void onFailure(String errorMessage) {
System.out.println("AHH!\n" + errorMessage);
}
}


The output from this code is the following:


i am not waiting for the query, so I can do other tasks

processing the query

YES!

query get all data result: very good



No comments:

Post a Comment