Understanding Synchronous, Asynchronous Calls and Callbacks in Java
This article explains the differences between synchronous and asynchronous method calls, introduces callback mechanisms, and provides complete Java code examples for both sync and async callbacks, helping developers grasp how to design and implement these patterns in backend applications.
Calling and Callback Mechanisms
In any application system, modules inevitably call each other; the invocation methods can be classified into several types.
1. Synchronous Call
Synchronous call is the most basic and simple form: method a() in class A calls method b() in class B and waits until b() finishes before continuing. It is suitable when b() executes quickly; otherwise the whole flow may be blocked.
2. Asynchronous Call
Asynchronous call solves the blocking problem of synchronous calls. Class A starts a new thread to invoke class B's method b(); the code proceeds immediately, so the execution of a() is never blocked regardless of how long b() runs.
If a() later needs the result of b(), it must listen for the result, e.g., using Future + Callable in Java.
http://www.cnblogs.com/xrq730/p/4872722.html
3. Callback
Callback is a bidirectional invocation method; it can be synchronous or asynchronous. The typical flow is: class A's a() calls class B's b(); after b() finishes, it actively calls A's callback() method.
Class A's a() method calls class B's b() method.
Class B's b() method, after execution, invokes class A's callback() method.
In simple terms, A calls B's method C, and B calls back A's method D, which is the callback method.
Types of Callbacks
Callbacks are divided into synchronous and asynchronous. Using a lottery scenario: buying a ticket and waiting for the result is a synchronous callback (must wait); buying a ticket and doing other things while waiting for the result is an asynchronous callback.
Synchronous Callback
Synchronous callback behaves like a normal call; if the called API takes a long time, the caller must wait, which blocks the flow.
Example
public interface OrderResult {
/**
* Order status
* @param state
* @return
*/
String getOrderResult(String state);
} public class Store {
@Getter @Setter
private String name;
public Store(String name) { this.name = name; }
/** Callback function: pass the structure to a method we cannot call directly and get the result */
public String returnOrderGoodsInfo(OrderResult order) {
String[] s = {"订购中...", "订购失败", "即将发货!", "运输途中...", "已在投递"};
Random random = new Random();
int temp = random.nextInt(5);
String s1 = s[temp];
return order.getOrderResult(s1);
}
} public class SyncBuyer implements OrderResult {
@Getter @Setter private Store store;
@Getter @Setter private String buyerName;
@Getter @Setter private String goodsName;
public SyncBuyer(Store store, String buyerName, String goodsName) {
this.store = store; this.buyerName = buyerName; this.goodsName = goodsName;
}
public String orderGoods() {
String goodsState = store.returnOrderGoodsInfo(this);
System.out.println(goodsState);
myFeeling();
return goodsState;
}
public void myFeeling() {
String[] s = {"有点小激动", "很期待!", "希望是个好货!"};
Random random = new Random();
int temp = random.nextInt(3);
System.out.println("我是" + getBuyerName() + ", 我现在的感觉: " + s[temp]);
}
@Override
public String getOrderResult(String state) {
return "在" + getStore().getName() + "商店订购的" + getGoodsName() + "玩具, 目前的预订状态是: " + state;
}
} public class Test2Callback {
public static void main(String[] args) {
Store wallMart = new Store("沙中路沃尔玛");
SyncBuyer syncBuyer = new SyncBuyer(wallMart, "小明", "超能铁扇公主");
System.out.println(syncBuyer.orderGoods());
}
}Asynchronous Callback
The code difference between sync and async callbacks is whether a new thread is created when invoking the third‑party API.
Example
public interface OrderResult {
String getOrderResult(String state);
} public class Store {
@Getter @Setter private String name;
public Store(String name) { this.name = name; }
public String returnOrderGoodsInfo(OrderResult order) {
String[] s = {"订购中...", "订购失败", "即将发货!", "运输途中...", "已在投递"};
Random random = new Random();
int temp = random.nextInt(5);
String s1 = s[temp];
return order.getOrderResult(s1);
}
} public class NoSyncBuyer implements OrderResult {
@Getter @Setter private Store store;
@Getter @Setter private String buyerName;
@Getter @Setter private String goodsName;
public NoSyncBuyer(Store store, String buyerName, String goodsName) {
this.store = store; this.buyerName = buyerName; this.goodsName = goodsName;
}
public String orderGoods() {
String goodsState = "--";
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr);
t.start();
System.out.println(goodsState);
goodsState = mr.getResult();
myFeeling();
return goodsState;
}
public void myFeeling() {
String[] s = {"有点小激动", "很期待!", "希望是个好货!"};
Random random = new Random();
int temp = random.nextInt(3);
System.out.println("我是" + getBuyerName() + ", 我现在的感觉: " + s[temp]);
}
@Override
public String getOrderResult(String state) {
return "在" + getStore().getName() + "商店订购的" + getGoodsName() + "玩具, 目前的预订状态是: " + state;
}
private class MyRunnable implements Runnable {
@Getter @Setter private String result;
@Override
public void run() {
try {
Thread.sleep(10000);
result = store.returnOrderGoodsInfo(NoSyncBuyer.this);
} catch (InterruptedException e) {
// log error
}
}
}
} public class Test2Callback {
public static void main(String[] args) {
Store wallMart = new Store("沙中路沃尔玛");
SyncBuyer syncBuyer = new SyncBuyer(wallMart, "小明", "超能铁扇公主");
System.out.println(syncBuyer.orderGoods());
System.out.println();
Store lawson = new Store("沙中路罗森便利店");
NoSyncBuyer noSyncBuyer = new NoSyncBuyer(lawson, "cherry", "变形金刚");
System.out.println(noSyncBuyer.orderGoods());
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
