Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mention dangers around Task and sending a lot of data along #13173

Merged
merged 2 commits into from
Dec 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions lib/elixir/lib/task.ex
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,38 @@ defmodule Task do
means that, if the caller crashes, the task will crash
too and vice-versa. This is on purpose: if the process
meant to receive the result no longer exists, there is
no purpose in completing the computation.
no purpose in completing the computation. If this is not
desired, you will want to use supervised tasks, described
in a subsequent section.

If this is not desired, you will want to use supervised
tasks, described next.
## Tasks are processes

Tasks are processes and so data will need to be completely copied
to them. Take the following code as an example:

large_data = fetch_large_data()
task = Task.async(fn -> do_some_work(large_data) end)
res = do_some_other_work()
res + Task.await(task)

The code above copies over all of `large_data`, which can be
resource intensive depending on the size of the data.
There are two ways to address this.

First, if you need to access only part of `large_data`,
consider extracting it before the task:

large_data = fetch_large_data()
subset_data = large_data.some_field
task = Task.async(fn -> do_some_work(subset_data) end)

Alternatively, if you can move the data loading altogether
to the task, it may be even better:

task = Task.async(fn ->
large_data = fetch_large_data()
do_some_work(large_data)
end)

## Dynamically supervised tasks

Expand Down
Loading