Зміст курсу
Multithreading in Java
Multithreading in Java
Basics of Asynchronous Programming
Here, we will explore what asynchronous programming is and how it differs from multithreading. There won't be any extensive practical examples in this section, as we will cover those in the next chapters. For now, we will focus more on the theory.
What is Asynchronous Programming?
Imagine a web server that handles requests from users. When a user makes a request to retrieve data from the database, the server can use asynchronous programming to start this request and continue processing other requests without waiting for the operation to complete. This way, the server won't remain idle while waiting for a response from the database!
Note
With asynchronous programming, the operation is akin to preparing several dishes simultaneously.
Callbacks
Callbacks are a key aspect of asynchronous programming. They enable you to execute specific actions once the task is finished, without blocking the main program thread.
For example, when you make an asynchronous request to a server, the callback function will be invoked when the server sends back a response.
What then is the Difference Between Multithreading and Asynchrony?
In a broad sense, multithreading is the capability of a program to carry out multiple tasks at the same time by utilizing different threads of execution.
Imagine a restaurant where cooks (threads) work simultaneously on different dishes. One cook is making soup, another is grilling a steak, and a third is cutting vegetables. Each cook works independently, but they all work at the same time to serve customers faster.
Imagine a restaurant where one cook (main thread) is preparing a complex dish, but he needs to wait for the water to boil (background task). Instead of standing and waiting (blocking), the cook can do other work, like chopping vegetables. When the water boils, he will receive a notification and continue cooking the dish.
Asynchrony in Java can be Represented by such Classes/Interfaces:
Future
(we studied): An interface that represents the result of an asynchronous computational task. Methods allow you to check if the task is complete, wait for it to complete, and get the result;CompletableFuture
(what we'll study in the next chapter): a class that implements theFuture
interface, providing facilities for building complex asynchronous computations. Methods allow you to combine tasks, handle errors, and perform actions after tasks are completed;Executor
: An interface that provides an execute method that takes a task as aRunnable
and executes it asynchronously;ExecutorService
(we studied): ExtendsExecutor
by adding methods to manage the lifecycle and execute tasks that return a result.
Summary
Asynchronous programming helps you create more responsive and efficient applications by avoiding lockups and providing better resource utilization.
Дякуємо за ваш відгук!