A call to an LLM takes seconds, and almost all of that time your program is waiting: for the network, for the model, for the next token. If you need ten answers, doing them one after another wastes most of a minute.
Java gives you several ways out: thread pools with CompletableFuture, and since Java 21, virtual threads that make blocking cheap. Python’s main answer for this kind of waiting is async: async def, await, and an event loop that runs many tasks on a single thread, switching between them whenever one is waiting.
This is part 12 of Python for Java Developers. Part 11 covered with and generators, which have async versions you’ll meet below.
The three words
import asyncio
from anthropic import AsyncAnthropic
client = AsyncAnthropic()
async def ask(question: str) -> str: # 1. async def: this function can pause
reply = await client.messages.create( # 2. await: pause here until the result is ready
model="claude-sonnet-5-5",
max_tokens=300,
messages=[{"role": "user", "content": question}],
)
return reply.content[0].text
answer = asyncio.run(ask("What is RAG?")) # 3. asyncio.run: start the event loop
async defdefines a coroutine function: a function that can pause in the middle.awaitis where it pauses. While this call waits on the network, the event loop runs other coroutines.asyncio.run()starts the event loop and runs your top-level coroutine to completion.
Notice AsyncAnthropic instead of Anthropic. Most AI SDKs ship a sync client and an async client; inside async code, you must use the async one.
The real win: many calls at once
One await on its own is no faster than a normal call. The payoff comes when you start several and wait for all of them:
var questions = List.of("What is RAG?", "What is an agent?", "What is a vector DB?");
var futures = questions.stream()
.map(q -> CompletableFuture.supplyAsync(() -> ask(q), executor))
.toList();
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
var answers = futures.stream().map(CompletableFuture::join).toList();async def main():
questions = ["What is RAG?", "What is an agent?", "What is a vector DB?"]
answers = await asyncio.gather(*(ask(q) for q in questions))
for q, a in zip(questions, answers):
print(q, "->", a[:60])
asyncio.run(main())asyncio.gather starts all the coroutines, waits for all of them, and returns their results in the same order as the inputs. Three 4-second calls take about 4 seconds, not 12. The * spreads the generator of coroutines into separate arguments (part 5 explains the star).
Python 3.11 added TaskGroup, a structured alternative much like Java’s structured concurrency: if one task fails, the others are cancelled.
async def main():
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(ask(q)) for q in questions]
answers = [t.result() for t in tasks] # all done when the block exits
How it compares with Java
Java threads + CompletableFuture |
Java virtual threads | Python asyncio |
|
|---|---|---|---|
| Unit of work | A task on a thread pool | A cheap thread per task | A coroutine on one event loop |
| Where it waits | Blocks a pool thread | Parks the virtual thread | Pauses at every await |
| Code style | Callbacks or join() |
Plain blocking code | async/await keywords |
| Run many, wait all | CompletableFuture.allOf |
ExecutorService + invokeAll |
asyncio.gather / TaskGroup |
| Blocking call inside? | Wastes a pool thread | Fine | Freezes everything |
The big conceptual difference: virtual threads let Java keep writing ordinary blocking code. Python makes every waiting point explicit with await, and in return runs everything on one thread with no locks needed for your own state.
The rules that keep you out of trouble
awaitonly works insideasync def. And once a function awaits something, it must beasynctoo, so async spreads upward through your call chain. Frameworks like FastAPI run the event loop for you, so endpoints can simply beasync def.- Calling an async function without
awaitdoes nothing useful.ask("hi")returns a coroutine object, not an answer, and Python warns:coroutine 'ask' was never awaited. - Never block inside async code.
time.sleep(2),requests.get(...)or a sync SDK client stops the whole event loop, so every other task freezes. Useawait asyncio.sleep(2), an async HTTP client such ashttpx.AsyncClient, and async SDK clients. - Call
asyncio.run()once, at the top of a script. Don’t call it inside a function that’s already running in an event loop.
If you must call blocking code from async code, push it to a thread so the loop stays free:
text = await asyncio.to_thread(extract_pdf_text, path) # runs in a worker thread
Timeouts and limiting concurrency
Two things you’ll need as soon as you call a real API:
async def ask_with_timeout(q):
async with asyncio.timeout(30): # Python 3.11+: cancel after 30 seconds
return await ask(q)
limit = asyncio.Semaphore(5) # at most 5 calls in flight
async def ask_limited(q):
async with limit:
return await ask(q)
answers = await asyncio.gather(*(ask_limited(q) for q in questions))
The semaphore works like java.util.concurrent.Semaphore: with 200 questions, only five requests run at a time, which keeps you under the provider’s rate limit.
async with and async for
Context managers and generators from part 11 have async versions. They mean what you’d expect: with and for, but allowed to wait in between.
async with client.messages.stream(model=MODEL, max_tokens=500, messages=messages) as stream:
async for text in stream.text_stream:
print(text, end="", flush=True)
That’s async streaming: one event loop can stream answers to hundreds of users at once.
What about threads and the GIL?
Python has threads too (threading, concurrent.futures.ThreadPoolExecutor, which looks very much like Java’s ExecutorService). For waiting on I/O, threads work fine. But the standard Python interpreter has a Global Interpreter Lock (GIL), which lets only one thread run Python code at a time, so threads don’t speed up CPU-heavy work. For that, Python uses separate processes (multiprocessing) or libraries written in C, like NumPy. Newer Python versions offer an optional build without the GIL, but it isn’t the default yet.
For LLM apps, which spend their time waiting on the network, async is the usual choice.
Traps for Java developers
- Forgetting
await. You get a coroutine object instead of a result, and a “never awaited” warning. - Mixing sync and async clients. A sync SDK call inside
async defblocks the loop. This is the most common bug in AI-generated async code. - Expecting parallel CPU work. async interleaves waiting; it doesn’t run Python code on several cores.
gatherwithout a limit. Firing 1,000 requests at once will hit rate limits. Use aSemaphore.
Key takeaways
async defdefines a function that can pause;awaitis where it pauses;asyncio.runstarts the loop.asyncio.gather(orTaskGroup) runs many calls at once, likeCompletableFuture.allOf.- Everything runs on one thread, so a single blocking call freezes every task.
- Use async clients,
asyncio.sleep,asyncio.timeoutand aSemaphorefor real API work. async withandasync forare the waiting versions ofwithandfor.- Threads exist, but the GIL means they help with I/O, not CPU-heavy Python code.
Frequently asked questions
What is the Python equivalent of CompletableFuture?
A coroutine started as a task. asyncio.create_task(coro) is like supplyAsync, await task is like join(), and asyncio.gather(...) is like CompletableFuture.allOf(...) followed by collecting the results.
Is Python async the same as multithreading?
No. Async runs many coroutines on one thread, switching between them at each await. Threads run on several OS threads. Async is lighter and safer for I/O-heavy work like API calls; neither speeds up CPU-heavy Python code because of the GIL.
When should I use async in Python?
When your program spends most of its time waiting on the network: calling LLM APIs, serving many web requests, or fetching many URLs. For simple scripts that make one call at a time, normal synchronous code is simpler.
What does asyncio.gather do?
It runs several coroutines concurrently, waits until all of them finish, and returns their results as a list in the order you passed them in. If one fails, the exception is raised from gather.
What is the GIL in Python?
The Global Interpreter Lock in standard CPython, which allows only one thread to execute Python code at a time. It keeps the interpreter simple and safe, but means threads don’t make CPU-bound Python code faster.
Next in the series: Python pip, venv and uv vs Maven, the last part, on modules, packages and project setup.
Comments