# Asynchronous programming

Asynchronous programming is a method of parallel computer programming that enables a process to run separately from the primary function of the program. Once the process completes, it communicates this information and may impact the primary function. Asynchronous programming often helps reduce or prevent wait times or lags in computer programming by enabling processes to continue to run in the background of the primary application.

### How does asynchronous programming work? <a href="#asynchronousprogramming-howdoesasynchronousprogrammingwork" id="asynchronousprogramming-howdoesasynchronousprogrammingwork"></a>

When you use asynchronous programming, you create an event loop. This is a process that waits for and dispatches events or messages, called a promise, in a program. As part of the event loop, you may create a callback, which allows the event loop to supply information from the program to another piece of code, typically the primary function of the program.

During that time, the application can perform other tasks while you await the program. This allows potentially taxing tasks to run without forcing the user to wait for their completion. Await is a function or operation of many programming languages that allows asynchronous programming.

### Asynchronous programming vs. synchronous programming <a href="#asynchronousprogramming-asynchronousprogrammingvs.synchronousprogramming" id="asynchronousprogramming-asynchronousprogrammingvs.synchronousprogramming"></a>

Both asynchronous and synchronous programming involve similar concepts within the broader field of computer programming. Synchronous or sequential programming is when tasks occur separately or one after another. The program pauses while the system performs the action and only responds once it receives the result. It features a single-thread model, meaning that it only performs a single action at a time.

Asynchronous programming differs in that it allows multiple tasks to run at the same time, and the programmer can often manage these tasks directly. It allows programs to continue to run even after you start a specific action.

### Benefits of asynchronous programming <a href="#asynchronousprogramming-benefitsofasynchronousprogramming" id="asynchronousprogramming-benefitsofasynchronousprogramming"></a>

There are several benefits associated with asynchronous programming, including:

* **It provides an improved user experience.** Asynchronous operations can improve the overall user experience since it helps systems run more efficiently. It helps reduce wait times, which often inconvenience customers.
* **It helps improve an application's performance.** This type of programming can also help improve an application's speed, responsiveness and overall performance.
* **It's applicable in a broad range of programming languages.** While asynchronous programming can make coding more complex, it's possible to apply the technique to a variety of languages with different syntaxes.
* **It can improve the speed of a program.** Since asynchronous programming allows a program to run multiple processes at the same time, even though they may take different periods to function, it can help the program complete its processes faster.
* **It creates efficient memory management.** Asynchronous programming can search for data in a memory set, such as a database, while performing other functions, making memory management faster for an application.

### When to avoid asynchronous programming <a href="#asynchronousprogramming-whentoavoidasynchronousprogramming" id="asynchronousprogramming-whentoavoidasynchronousprogramming"></a>

While there are many positive uses for asynchronous programming, it's not always the best option. When executing code that calls for accessing and updating stored data, which multiple processes may access, asynchronous performance may not be the ideal option. Changing records in one process while another tries to access them can lead to inaccurate or corrupted data.

### Approaches for Asynchronous Programming <a href="#asynchronousprogramming-approachesforasynchronousprogramming" id="asynchronousprogramming-approachesforasynchronousprogramming"></a>

There are two commonly used approaches for Asynchronous Programming as mentioned below:

* Callbacks with `CompletableFuture`
* `Future` and `ExecutorService`

#### Callbacks with CompletableFuture <a href="#asynchronousprogramming-callbackswithcompletablefuture" id="asynchronousprogramming-callbackswithcompletablefuture"></a>

The `CompletableFuture` is a class introduced in Java 8 that facilitates asynchronous programming using the callback-based approach. It represents a promise that may be asynchronously completed with the value or an exception. It provides various methods like `supplyAsync`, `runAsync`, and `thenApplyAsync` for asynchronous programming. We don’t need to use the `ExecutorService` explicitly. The `CompletableFuture` internally uses `ForkJoinPool` to handle the task asynchronously.

```
CompletableFuture
    .supplyAsync(new SomeService())
    .thenAccept(result -> System.out.println(result))
    .exceptionally(e -> { e.printStackTrace(); return null;})
    .thenRun(() -> System.out.println("Wrap-up!"));
```

#### Future and ExecutorService <a href="#asynchronousprogramming-futureandexecutorservice" id="asynchronousprogramming-futureandexecutorservice"></a>

The `Future` and `ExecutorService` can be used for the asynchronous programming in a more traditional way. The `ExecutorService` allows you to submit tasks for the asynchronous execution.

```
ExecutorService executor = Executors.newFixedThreadPool(THREADS_COUNT);

Callable<String> task = () -> {
    TimeUnit.MILLISECONDS.sleep(500);
    return "Task executed!";
};

Future<String> future = executor.submit(task);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.leapwise.co/backend-handbook/software-design-principles-and-clean-code/asynchronous-programming.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
