Junior — Middle
Have you worked with the CompletableFuture class for asynchronous programming in Java?
sobes.tech AI
Answer from AI
Yes, the CompletableFuture class in Java is used for convenient and efficient asynchronous programming. It allows running tasks in a separate thread and processing their results upon completion, supports chaining, exception handling, and combining multiple asynchronous operations.
Example of using CompletableFuture:
import java.util.concurrent.CompletableFuture;
public class Example {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
// Long operation
return "Result";
})
.thenApply(result -> {
// Process result
return result.toUpperCase();
})
.thenAccept(finalResult -> {
System.out.println("Final result: " + finalResult);
});
// To prevent the program from ending immediately
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
This class is widely used for building non-blocking, scalable applications.