Using fromCallable for Non-Blocking Database Calls in Java

In continuation to previous post: https://lnkd.in/gyASSi7Q We have been talking till now about theories around fromCallable and fromRunnable. Question comes: how to use one and when to use one. In this post I would cover fromCallable. By using fromCallable, you direct the system “Don’t call this until someone asks for”. You heard this right. It is as simple as that. Let’s take an example of fetching user data from database. In imperative coding in Java, database would get hit immediately even if it is not required by that time. Seeing the two side-by-side is the only way to really understand the prowess of the reactive approach. It’s all about getting rid of those blocking hurdles. In the reactive world, the thread is free to handle other tasks while the data is being fetched. Look at this code. The thread sits idle while fetchUser does its thing. public User getAndProcessUser(String id) { // Thread stops here and waits... User user = service.fetchUser(id); user.setName(user.getName().toUpperCase()); return user; } Now, look at the reactive version. We wrap the call and transform the data as a stream. public Mono<User> getAndProcessUserReactive(String id) { return Mono.fromCallable(() -> service.fetchUser(id)) .map(user -> { user.setName(user.getName().toUpperCase()); return user; }); } In the first example, if the database takes 2 seconds, your thread is dead for 2 seconds. In the second example, using fromCallable, the system only executes the call when a subscriber is ready, and it doesn't hold the thread hostage while waiting. Once you start scaling to thousands of users, this is the difference between a system that stays balanced and one that just crashes. We’ll talk about defer and how to handle more complex "fresh data" scenarios in the next post.

View profile for Gaurav Raj

In continuation to previous post https://bit.ly/4bsoGg0 Once you get basics of Reactive programming, it becomes more interesting as we delve into further details. Let's talk about further components which come from libraries like Project Reactor. There are something called Mono and Flux. Both are different types of Publishers supported in reactive programming. Understanding these is as simple as reading a line of code. With the concept of Mono and Flux, you deal with a stream of data and not just the static data itself. Lets break it with an example. When we are fetching a unique user from a database based on id, we use Mono. Mono deals with fetching at most one object (0 or 1) or an error. Flux can be used to fetch 0 to N number of items, like a list of active users from a database. Instead of going into more details and confusing you, let's talk about other buzz words we use in reactive programming. Operators: In reactive programming, we don't just "get" data. We transform it as it flows. There are different operators which can be used for transformation without those for-loops which we were bound to use in imperative Java. Map: For synchronous transformation, like changing the type of a variable on the fly. FlatMap: Used for asynchronous transformations, like performing a database call for every item in a Flux. Filter: Filter out only the data which meets a given criteria. Concept of Backpressure: A very critical concept which should be carefully used in reactive programming; otherwise, the situation could go worse than imperative programming. Backpressure is a concept where the consumer can send a signal to the producer like "Hey, slow down, I can only handle five items at a time right now." In this way, the system maintains its own balance and eventual crashing of an application can be prevented. A Simple Example: Look at the logic below. In older Java, you'd wait for the whole list. In Reactive, you handle it as it comes. The stream starts, filters out the "C++" hurdle, transforms the rest, and then finally prints them. No curly brace hurdles, no complex declarations. Trust me, once you start thinking in streams, going back to the old way feels like taking a step backward. It might take extra time to master the operators, but the ultimate satisfaction of building a non-blocking, resilient system is worth the effort.

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories