SoFunction
Updated on 2025-03-08

Sample code for implementing synchronous callbacks in java

Synchronous callback is a programming mode in which the callback function is executed synchronously in the code that calls it. Simply put, it is to wait for it to complete where the callback function is called, and then continue to execute subsequent code.

In Java, you can use interfaces and implementations to implement synchronous callbacks. Here is a simple example:

Define the callback interface:

public interface Callback {
    void onComplete(String result);
}

Implementing the callback interface:

public class MyCallback implements Callback {
    @Override
    public void onComplete(String result) {
        ("Callback received result: " + result);
    }
}

Use the callback interface:

public class Processor {
    private Callback callback;

    public Processor(Callback callback) {
         = callback;
    }

    public void process() {
        // Simulate some processing        try {
            (1000); // 1 second delay        } catch (InterruptedException e) {
            ();
        }

        // Call callback function        ("Process Completed");
    }
}

Main program:

public class Main {
    public static void main(String[] args) {
        // Create a callback object        Callback myCallback = new MyCallback();
        
        // Create a processor and pass in a callback object        Processor processor = new Processor(myCallback);
        
        // Execute processing        ();
        
        // The main thread waits for processing to complete        ("Main thread continues...");
    }
}

In this example:

  • Callback is an interface that defines the callback method onComplete.
  • MyCallback is an implementation of the Callback interface, which defines the specific behavior of callbacks.
  • The Processor class accepts a Callback implementation and calls this callback after processing is completed.
  • In the Main class, we create a MyCallback instance, pass it to the Processor object, and finally call the process method to simulate the processing.

The callback function is called synchronously in the Processor process method. The output in the Main class will be displayed only after the callback is executed, showing the characteristics of synchronous callbacks.

This is the end of this article about Java's example code to implement synchronous callbacks. For more related Java synchronous callback content, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!