DEV Community

Partha Sutradhar
Partha Sutradhar

Posted on

3 1 1 1

Design Callback Pattern in Java for WorkerContext

Introduction

Callbacks are a prominent programming paradigm in Java that is used for asynchronous and event-driven programming. Callbacks were traditionally created and used by establishing interfaces and putting them into anonymous inner classes, which could result in verbose and crowded code. But lambda expressions, which offer a more concise and expressive method of working with callbacks, were introduced in Java 8.

We'll look at a real-world example in this blog article to see how lambda expressions can make using callbacks in Java easier. We will compare the lambda approach with the old method using a WorkerContext class that uses callbacks to accomplish some work.

Design Callback Pattern

Let's begin by discussing the traditional approach to callbacks pattern in Java.

interface Callback {
    void call(int data);
}

class WorkerContext {
    private Callback callback;

    public WorkerContext() {}

    public WorkerContext(Callback callback) {
        this.callback = callback;
    }

    public void startWork(int min, int max) {
        if (callback != null) {
            callback.call(ThreadLocalRandom.current().nextInt(min, max + 1));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The conventional way involves defining a Callback interface with a single call method, utilising an anonymous inner class to generate an instance of the interface, and passing it to the WorkerContext.

Traditional Way

class Solution {
    public static void main(String[] args) {
        Callback callback = new Callback() {
            @Override
            public void call(int data) {
                System.out.println("Random : " + data);
            }
        };
        WorkerContext workerContext1 = new WorkerContext(callback);
        workerContext1.startWork(0, 100);
    }
}
Enter fullscreen mode Exit fullscreen mode

Lambda Way

Now, let's explore how lambda expressions can simplify the callback process.

class Solution {
    public static void main(String[] args) {
        WorkerContext workerContext2 = new WorkerContext((count) -> System.out.println("Random : " + count));
        workerContext2.startWork(0, 100);
    }
}
Enter fullscreen mode Exit fullscreen mode

When constructing the WorkerContext instance via the lambda method, we explicitly describe the callback at that point. As a result, anonymous inner classes and a separate interface specification are not required.

Conclusion

Using functional programming concepts in your Java applications is made possible by adopting the lambda approach, which also increases code readability and maintainability.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay