Make request thread to wait and notify

Introduction :

Let’s assume that in your application(not reactive), there is an API which depends on the response from event listeners.

In real time, we use lot of event listeners in event driven architectures. It can be

  • Another thread completion
  • Kafka consumer completion
  • Redis key state change, etc.,

Problem :

Let’s say we create an endpoint /get. In spring boot application, I’ve created a DTO class for response with two fields.

private boolean completed;
private String message;

Both the fields will be updated from another thread. Let’s consider the following code.

In the above code, GetResponse values are updated from the ExecutorService‘s Runnable. But If I make the request, the response will be

{
    "completed": false,
    "message": null
}

Actually request thread won’t wait for the Runnable execution.

Solve with CountDownLatch :

CountDownLatch is basically initialized with the counter and it’ll be decreased by using .countdown() method.

Till it reaches zero, the request thread will be blocked. So modifying the code with CountDownLatch objects.

In the above code, I’m only waiting for maximum of 2 seconds for thread completion. But we can make it wait for indefinite period with .await() method with no parameters.

To read more about CountDownLatch from the official documentation click here.

Code is available in github for consumption. https://github.com/ashoksl/java_samples/tree/master/blockrequest

Published