Sobes.tech
Junior

What is asynchronous execution?

sobes.tech AI

Answer from AI

Asynchronous programming is a method of executing operations where a task is started, and control is immediately returned to the calling code, allowing it to perform other tasks while the initiated operation completes in the background. The result of the operation is processed later. Main differences from synchronous programming:

  • Synchronous: The operation blocks the execution thread until it completes. The code waits for the result.
  • Asynchronous: The operation does not block the thread. The code continues executing, and the result is handled using callbacks, promises, or reactive streams.

Examples of usage:

  • Network requests (HTTP, databases)
  • Reading/writing large files
  • Long-running computations

In Java, asynchrony is implemented using:

  • Threads
  • Executors and thread pools
  • Future and CompletableFuture
  • Asynchronous frameworks (Netty, Akka, Reactor)

Example with CompletableFuture:

// Simulating an asynchronous operation
public CompletableFuture<String> performAsyncOperation() {
    return CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(1000); // Simulating delay
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        return "Result of async operation";
    });
}

// Usage
CompletableFuture<String> futureResult = performAsyncOperation();

// Main thread continues work
System.out.println("Main thread continues...");

// Handling the result when it's ready
futureResult.thenAccept(result -> {
    System.out.println("Result received: " + result);
});

// To wait for the future to complete if this is the end of the program
// futureResult.join(); // For demonstration, usually managed by a framework in real applications