Session 1 — Parallelism & Caching
Session 1Parallelism & Caching · 3h

Doing more things at once and never repeating work

Today you will understand why an application gets slow, how to get the computer working on several tasks at the same time, and how to keep results you have already calculated so you can answer in the blink of an eye. Everything is explained with everyday analogies and applied to Spring Boot.

  • Explain what a thread is and why parallelism exists
  • Use CompletableFuture and @Async in Spring
  • Configure thread pools and virtual threads
  • Avoid race conditions in Spring beans
  • Apply caching with @Cacheable, Caffeine and Redis
  • Recognise the risks of a badly designed cache

Why do applications get slow?

When you open an online shop and click on a product, your request travels to a server (a computer somewhere else), which fetches data from a database, perhaps asks another service for the price, calculates shipping and only then answers you. Each of these steps takes time.

Most of that time is not spent calculating. It is spent waiting: waiting for the database, the network, another service. The processor is almost idle, twiddling its thumbs.

The restaurant with a single waiter

Imagine a restaurant with only one waiter. He takes table 1's order to the kitchen and stands there, idle, until the dish is ready. Only then does he serve table 2. The tables wait for ages, yet the waiter spent almost all his time doing nothing. There are two ways to improve: hire more waiters (parallelism) or have dishes already prepared for the most common orders (caching). That is exactly what you will learn today.

What you will see in this session

0:00–0:40Module 1.1 · Concurrency fundamentals in Java
0:40–1:30Module 1.2 · Parallelism in Spring (+ lab)
1:30–1:40Break ☕
1:40–2:40Module 1.3 · Caching strategies (+ lab)
2:40–3:00Module 1.4 · Pitfalls and good practices

Three words you will hear a lot

LatencyHow long it takesThe time between making a request and receiving the answer. Measured in milliseconds (ms). 1000 ms = 1 second.
ThroughputHow much gets done per secondHow many requests the server can answer per second. A restaurant that serves 100 meals an hour has more throughput than one that serves 20.
ConcurrencySeveral things in progressSeveral tasks running during the same period of time, even if they take turns.

Threads: the workers of your program

A Java program runs inside a process (the JVM). Inside that process, the ones who actually execute the instructions are the threads («threads of execution»). Each thread follows the code line by line, independently of the others.

When you run a main, there is already one thread called main. If you create more threads, your program starts doing several things at the same time.

Threads are waiters

The process is the restaurant; the threads are the waiters. They all share the same kitchen (the memory). This is great, because they all see the same data, but it is also dangerous: two waiters may try to use the same pan at the same time.

Concurrency vs. parallelism

ConceptWhat it isAnalogy
ConcurrencySeveral tasks in progress, taking turns on the same processor.One cook who stirs the soup, flips the steak and goes back to the soup.
ParallelismSeveral tasks literally running at the same time, on different processors (cores).Three cooks, each at their own stove.

Creating a thread by hand

The () -> { … } is a lambda: a block of code passed around as if it were a value. Here it tells the thread «when you start, do this». start() creates the thread; join() waits for it to finish.

The order is not guaranteed

Run this program several times and the order of the messages may change. The operating system decides which thread runs at each moment, not you. This unpredictability is the main source of difficulty in concurrent programming.

See the difference: one by one or all at once

Imagine your service has to request data from three systems: the catalogue, the stock and the prices. Change the times and see what happens when the requests are made in sequence or in parallel.

The golden rule

In sequence, the total time is the sum of the times. In parallel, it is the time of the slowest task. You can only parallelise tasks that do not depend on each other.

Platform threads vs. virtual threads

Until Java 21, every Java thread corresponded to an operating system thread, which we call a platform thread. They are «expensive»: each one reserves about 1 MB of memory and the operating system has to manage switching between them (context switching). A normal server can handle a few thousand, not much more.

Java 21 brought virtual threads (Project Loom): lightweight threads managed by the JVM itself. When a virtual thread is waiting (for a database, for example), the JVM «takes it off» the real thread and puts another one to work there. You can have millions of them.

~1 MBPlatform threadMemory reserved by each one. Creating 10,000 is heavy and slow.
~1 KBVirtual threadStarts tiny and grows as needed. Creating 1,000,000 is feasible.
I/OWhere they shineTasks that spend their time waiting: HTTP, databases, files.
CPUWhere they don't helpHeavy calculations. There the limit is the number of processor cores.
Waiters vs. order tickets

A platform thread is a full-time waiter: expensive. A virtual thread is an order ticket: the waiter picks up a ticket, takes it to the kitchen, puts it down while the dish is being made and immediately picks up another ticket. A few waiters can handle thousands of tickets.

In parallel, you wait for the slowest one (500 ms). In sequence you would add them all up: 1000 ms. Parallelism saved half the time.

Executors and CompletableFuture

Creating threads by hand with new Thread() is like hiring a new waiter for each customer and firing him at the end. In practice we use a thread pool: a fixed group of threads that keep picking up tasks from a queue.

ExecutorService: the staffing agency

ToolWhat it is for
Executors.newFixedThreadPool(n)Pool with n fixed threads. A good starting point.
Executors.newVirtualThreadPerTaskExecutor()A new virtual thread per task (Java 21+). Ideal for I/O.
ForkJoinPoolSplits a big problem into pieces and joins the results. It is what powers parallel streams.

CompletableFuture: promises that chain together

A simple Future forces you to stand still at get(). A CompletableFuture lets you say «when this finishes, do that», without blocking. It is like ordering online: you get an order number and are only notified when it arrives.

MethodIn plain language
supplyAsync(() -> …)Starts a task on another thread and promises a result.
thenApply(r -> …)When the result arrives, transform it.
thenCompose(r -> …)When it arrives, start another asynchronous task that depends on it.
thenCombine(other, (a,b) -> …)Combine two independent results.
allOf(f1, f2, f3)Wait for all of them to finish.
exceptionally(e -> …)If something fails, return an alternative value.
orTimeout(2, SECONDS)Give up if it takes too long.

Try it: change the time of each service and simulate a failure in the pricing service.

Parallel streams: handle with care

list.parallelStream().map(…) splits the work across several cores automatically. It works well for heavy calculations on large lists. But it uses a pool shared by the whole JVM (the ForkJoinPool.commonPool()): if you put database or HTTP calls in there, you block that pool for the entire application. In Spring server code, it is rarely the right tool.

When threads trip over each other

Threads share memory. If two of them touch the same variable at the same time, the results may be wrong. These problems are treacherous because they do not always happen: the program works 99 times and fails on the hundredth.

Race condition: the race for the same variable

The instruction counter++ looks like a single one, but the computer does three steps: read the value, add 1, write. If two threads read the same value before either of them writes, one of the additions is lost.

Now at large scale: several threads, each adding many times. Compare the three versions.

SolutionHow it worksWhen to use it
synchronizedPuts a «lock» on it: only one thread enters the block at a time.Protecting several operations that must happen together.
AtomicInteger, AtomicLongThe processor does read-add-write in a single indivisible step.Counters and simple values.
ConcurrentHashMapA map built for many threads.Whenever a map is shared.
ImmutabilityObjects that never change (e.g. record) cannot be corrupted.Whenever possible. It is the simplest solution.

Deadlock and starvation

Deadlock 🔒🔒Thread 1 holds lock A and waits for B. Thread 2 holds B and waits for A. They are stuck forever. Like two cars at a narrow crossing, each waiting for the other to back up.
Starvation 🍽️A thread never gets its turn because others always jump ahead. Like the customer who is never served because VIP customers keep arriving.
Livelock 🔄Two threads keep giving way to each other forever, like two people in a corridor who always step aside to the same side.
How to avoid deadlocks

Always acquire locks in the same order throughout the code, keep synchronized blocks small and prefer high-level tools (ConcurrentHashMap, CompletableFuture) over manual locks.

The hidden danger in Spring: singleton beans

By default, Spring creates a single instance of each @Service, @Component or @RestController (singleton scope). That instance is used by all requests at the same time, each on its own thread. So a field inside a service is shared by every user!

If Ana and Bruno add items at the same time, Ana's item may end up in Bruno's cart.

Local variables live on each thread's stack and are never shared. Rule of thumb: Spring services should not have fields that change; only injected dependencies (repositories, other services) and constants.

The controller is a singleton: all requests share the same field. requestsToday++ is not atomic, so additions are lost. Use AtomicInteger or, better, a Micrometer metric (session 2).

Asynchronous execution with @Async

Sometimes you don't need a task's result to answer the user. Example: after an order, sending the confirmation email. The customer should not have to wait for the email server. With @Async, Spring runs that method on another thread and the request carries on.

Step 1: switch the feature on

Step 2: annotate the methods

Look at the names in square brackets: the HTTP request was handled by Tomcat's http-nio-8080-exec-3 thread; the email was sent by the task-1 thread, from Spring's executor. The customer received the answer 2 seconds before the email went out.

How it works inside: the proxy

Spring does not change your class. It creates a proxy: a «middleman» object placed in front of your service. When you call the method, the proxy receives the call and hands it over to another thread.

Controllercalls sendEmail()
→
Spring proxyintercepts and submits the task to the executor
→another thread
NotificationServiceyour code runs on thread task-1
The self-invocation trap

If a method in the same class calls the @Async method with this.sendEmail(), the call does not go through the proxy. Result: it runs on the same thread, synchronously, with no warning at all. The same happens with @Transactional and @Cacheable. Solution: put the asynchronous method in another bean and inject it.

What if the asynchronous method fails?

In an @Async method that returns void, the exception does not go back to the caller (it has already moved on). By default it only shows up in the log. To handle it, register an AsyncUncaughtExceptionHandler. In methods that return a CompletableFuture, the exception stays inside the promise and you handle it with exceptionally.

Spring annotations work through proxies. An internal call (this.method()) goes straight to the real object and @Async is silently ignored.

Configuring the pool: how many workers and how big a queue?

The executor that runs @Async methods is a ThreadPoolTaskExecutor. It has four parameters you really need to understand, because they decide how your application behaves under pressure.

ParameterMeaningIn the restaurant
corePoolSizeThreads always available.Permanent staff.
queueCapacityHow many tasks can wait in the queue.Seats in the waiting area.
maxPoolSizeMaximum number of threads, created only when the queue is full.Temporary staff called in on packed days.
Rejection policyWhat to do when everything is full.What to tell the customer when there is no more room.
A surprise that catches everyone out

The extra threads (above corePoolSize) are only created when the queue is full. If the queue is huge (or unbounded), you never go above the core. Try it in the simulator below.

The configuration in Spring Boot

This is the simplest way: Spring Boot creates the executor for you with these values.

Useful when you want separate pools per type of work. That way, if the email server gets slow, it does not block invoice generation. This is called a bulkhead (like the watertight compartments of a ship).

Rejection policies

PolicyWhat it doesIn practice
AbortPolicy (default)Throws TaskRejectedException.Fails fast and in the open.
CallerRunsPolicyWhoever submitted the task runs it themselves.Naturally slows down whoever is producing too much work (backpressure).
DiscardPolicySilently throws the task away.Dangerous: you lose work without knowing.
DiscardOldestPolicyDiscards the oldest task in the queue.Only for data where only the most recent matters.

Not losing the context: TaskDecorator

Some information lives «attached» to the thread: the authenticated user (SecurityContext), the request identifier in the logs (MDC), the trace. When the work jumps to another thread, that information is left behind. A TaskDecorator copies it.

Shortcut for security and tracing

For the authenticated user there is DelegatingSecurityContextAsyncTaskExecutor. For tracing (session 2), Spring Boot 3 has ContextPropagatingTaskDecorator, which propagates everything Micrometer knows about.

Virtual threads, scheduling and WebFlux

Turning on virtual threads in Spring Boot

With Java 21 and Spring Boot 3.2 or later, a single line is enough:

With this, Tomcat handles each HTTP request on a virtual thread, and @Async and @Scheduled also start using them. You don't need to change anything else in the code.

Simulate a service that receives many requests, each waiting 1 second for another system. Compare a pool of 200 platform threads (Tomcat's default) with virtual threads.

Pinning: when the virtual thread gets «stuck»

In Java 21 to 23, if a virtual thread waits inside a synchronized block, it becomes pinned to the real thread, and you lose the benefit. This was fixed in Java 24. On Java 21, prefer ReentrantLock in code that waits, and check with -Djdk.tracePinnedThreads=full. Another caveat: with thousands of simultaneous requests, the limit becomes the database. Virtual threads don't conjure up database connections out of nowhere (you will see this in session 2).

Scheduled tasks with @Scheduled

By default, all scheduled tasks share a single thread. If one takes long, the others are delayed. Increase it with spring.task.scheduling.pool.size=4 or turn on virtual threads.

Parallelism in batch processing (Spring Batch)

Multi-threaded stepA step that reads, processes and writes blocks (chunks) on several threads. Simple, but the reader must be thread-safe.
PartitioningSplits the data into parts (e.g. customers A–M and N–Z) and each part is processed by an independent worker.
Parallel stepsDifferent, independent steps run at the same time (e.g. importing customers and importing products).

Spring MVC with virtual threads or Spring WebFlux?

Spring WebFlux is the reactive alternative: instead of one thread per request, a few threads handle everything through events, and the code uses the Mono and Flux types.

Spring MVC + virtual threadsSpring WebFlux
Code styleNormal, line by line, easy to read and debug.Chains of operators; steeper learning curve.
LibrariesWorks with JPA, JDBC and everything that already exists.Requires reactive drivers (R2DBC, WebClient…).
Streaming and backpressureLimited.Excellent: continuous streams, SSE, WebSockets.
RecommendationThe default choice for new APIs in 2026.When you need streaming or already have a reactive codebase.

Lab 1: parallelising calls to external services

Goal: the order detail page calls three services, one after the other. You will make it faster with CompletableFuture and then compare it with virtual threads.

Starting point (slow)

Notice that customers and loyalty need the customerId, which comes from the order. The carrier only needs the id. There are dependencies, so you can't blindly parallelise everything.

Optimised version

Challenges lab

  1. Measure the times with Spring's StopWatch and record them in the log.
  2. Swap the executor for Executors.newVirtualThreadPerTaskExecutor(). Do the times change with few requests? And with 500 simultaneous requests?
  3. Simulate the carrier being down (throw an exception). Make sure the page still responds using exceptionally.

Cache: never doing the same work twice

A cache is a fast storage area where you keep the result of a slow operation, to reuse it next time. The second time, instead of going to the database (slow), you go to memory (very fast).

The sticky note on the monitor

You call directory enquiries to get the plumber's number. It takes 3 minutes. You write the number on a sticky note and stick it to your monitor. Next time, it takes you 2 seconds. The sticky note is the cache. But careful: if the plumber changes number, the sticky note is out of date. That is the big challenge with caches.

~0.0001 msMemory (RAM)Local cache, inside your application.
~0.5 msLocal networkDistributed cache such as Redis.
5–50 msDatabaseA typical query.
100–2000 msExternal serviceA third-party API over the internet.

Essential vocabulary

Hit
The value was in the cache. Fast answer. 🎯
Miss
It wasn't. You have to go to the (slow) source and then store it in the cache.
Hit ratio
Percentage of hits. A good cache typically has more than 80%.
Eviction
Removing entries from the cache, because it is full or because the value changed.
TTL
Time To Live: the maximum time an entry may live in the cache.

Usage patterns

PatternHow it worksAdvantage / risk
Cache-aside ⭐The application asks the cache; if it's not there, it goes to the database and stores the result in the cache.Simple and the most common. It is what @Cacheable does.
Read-throughThe application only talks to the cache; the cache goes to the database by itself.Cleaner code; needs a cache that knows how to load data (e.g. Caffeine's LoadingCache).
Write-throughWhen saving, it writes to the cache and to the database at the same time.Cache always up to date; slower writes.
Write-behindIt writes to the cache and the database is updated later, in batches.Lightning-fast writes; risk of losing data if the cache goes down.

When the cache fills up: eviction policies

LRULeast Recently Used. Out goes whatever hasn't been used for the longest. Like tidying your wardrobe and removing the clothes you haven't worn for the longest time.
LFULeast Frequently Used. Out goes whatever has been used the fewest times in total.
TTLEach entry has an expiry date, like a yoghurt. Once it expires, it goes.
W-TinyLFUCaffeine's algorithm: combines frequency and recency. An excellent hit ratio in practice.

Try a cache from the inside

Click on the products to request them. Each product's first request is a miss (800 ms); the following ones are hits (1 ms), until the entry leaves the cache. Change the capacity and the policy.

Local or distributed cache?

Local (Caffeine)Distributed (Redis)
Where it livesIn the memory of each application instance.On a separate server, shared by all instances.
SpeedNanoseconds.Sub-millisecond (there is a network round trip).
ConsistencyEach instance has its own copy: they may diverge.Everyone sees the same value.
Survives restarts?No.Yes.
Ideal forSmall data, read a lot, that rarely changes (settings, catalogues).Sessions, shared data, applications with several instances.

Caching in Spring with four annotations

Spring has a cache abstraction: you annotate the methods and it takes care of the rest. The best part is that the code doesn't depend on the technology: you can swap Caffeine for Redis without changing a single line of the service.

Step 1: dependency and activation

Step 2: the annotations

AnnotationWhat it does
@Cacheable("products")Before running the method, it looks in the cache. If the value is there, it returns it immediately and the method doesn't even run. If not, it runs and stores the result.
@CachePut("products")Always runs the method and updates the cache with the result. For writes.
@CacheEvict("products")Removes from the cache. With allEntries = true it clears everything.
@Caching(…)Combines several of the above on the same method.

Test the API. Look at the response time and at the server messages underneath.

Controlling keys and conditions

The key identifies the entry in the cache. By default it uses the method's parameters. With key, condition and unless you write rules in SpEL (Spring Expression Language), a mini-language that starts with #.

AttributeEvaluatedMeaning
conditionBefore running the methodIf false, the cache is ignored entirely.
unlessAfter running the methodIf true, the result is not stored. Can use #result.
Cached objects should be immutable

In a local cache, the object returned is the same one that is stored. If someone does product.setPrice(0) on the object they received, they have changed the cache for everyone! Use record or immutable DTOs.

@CachePut always runs the method and stores the result. @Cacheable wouldn't run the method if the product were already cached. @CacheEvict would also be valid, but would force a trip to the database on the next request.

Choosing the technology: Caffeine, Redis or both

With no configuration, Spring uses a simple ConcurrentHashMap, which never expires and never frees memory. It's fine for learning, never for production. Choose a proper provider:

maximumSize limits the number of entries; expireAfterWrite is the TTL; recordStats turns on hit and miss statistics (so you can see them in the Actuator).

To configure each cache differently:

Redis stores bytes, so objects have to be serialised (converted into text or binary). The default uses Java serialisation, which is fragile and unreadable. Prefer JSON:

In applications with several instances and a lot of traffic, the two are combined: a small, lightning-fast local cache in front of a shared Redis cache.

L1 · Caffeinein each instance · short TTL (30 s) · nanoseconds
↓ miss
L2 · Redisshared · long TTL (10 min) · ~0.5 ms
↓ miss
Databasethe source of truth · 5–50 ms

Spring doesn't ship this ready-made. It is implemented with a custom CacheManager or with libraries such as JetCache. The problem to solve is invalidation: when a product changes, every instance has to clear its L1, usually through Redis pub/sub messages.

Caching in the persistence layer (Hibernate)

LevelScopeNotes
1st levelWithin a transaction (EntityManager).Always on. If you ask for the same entity twice in the same transaction, there is only one query.
2nd levelShared between transactions.Optional. Stores entities by ID. Good for reference tables (countries, categories).
Query cacheQuery results.Invalidated whenever any table involved changes. Rarely worth it.
Spring Cache or Hibernate's cache?

In most cases, @Cacheable on services is simpler, more visible, and caches ready-made DTOs (not entities with lazy associations). Use the 2nd-level cache for reference entities that are read a lot.

HTTP caching: let the browser do the work

The fastest cache is the one that never even reaches the server. With the right headers, the browser (or a CDN) stores the responses.

1st requestServer answers 200 + ETag: "7"
→
Next requestBrowser sends If-None-Match: "7"
→
Nothing changedServer answers 304 Not Modified, with no body. Saves bandwidth.

The ShallowEtagHeaderFilter generates ETags automatically from the response content. It saves network traffic, but the server still computes the whole response.

When the cache turns against you

«There are only two hard things in computer science: cache invalidation and naming things.» The saying is old, but still true. Know the classic problems:

🐘 Cache stampedeA very popular entry expires. In the same second, 1000 requests get a miss and all go to the database, which falls over.
Solution: sync = true, TTL with random variation (jitter) or refresh before expiry (Caffeine's refreshAfterWrite).
🕳️ Cache penetrationRequests for keys that don't exist (e.g. /products/999999) are never cached and always hit the database. It may be an attack.
Solution: cache the «doesn't exist» with a short TTL or use a Bloom filter.
🥛 Stale dataThe price changed in the database, but the cache keeps showing the old one.
Solution: a TTL suited to the business, @CacheEvict/@CachePut on every write.
🧠 Unbounded cacheThe cache grows until memory blows up (OutOfMemoryError).
Solution: always set maximumSize. You will see this in session 2.

Invalidation with several instances

With 3 instances of the application and local caches, a @CacheEvict only clears the instance that handled the request. The other two keep the old value until the TTL expires. Options: accept the staleness for a short TTL, use Redis (a single cache) or broadcast invalidation events.

Measure: is the cache really helping?

With the Actuator and recordStats, Spring Boot publishes metrics for each cache automatically:

Decision checklist

QuestionIf the answer is «yes»…
Does the task spend its time waiting for I/O, and are there several independent ones?Parallelise (CompletableFuture, virtual threads).
Does the task not need an immediate answer?@Async or a message queue.
Is the same data read many times and does it rarely change?Cache.
Must the data be 100% up to date (bank balance, stock at checkout)?Don't cache it, or use a very short TTL.
Is the problem a slow query due to a missing index or N+1?Neither parallelism nor caching: fix the query (session 2).
Haven't you measured where the slowness is yet?Measure first. Optimising blindly is a waste of time.
Remember

Parallelism and caching add complexity and new kinds of bugs. Use them where measurement shows they make a difference, not just as a precaution.

Exercises

1. A thread-safe visit counter easy

A @RestController counts visits with an int field. Fix it so it works with many simultaneous requests.

Show solution

2. Asynchronous email with its own pool medium

Create an emailExecutor with 2 core threads, 4 maximum, a queue of 50 and CallerRunsPolicy. Use it in an @Async method that simulates a 2-second send.

Show solution

3. Exchange-rate cache medium

A service ExchangeService.rate(String currency) calls an external API (1 s). Rates may be up to 60 seconds out of date. Configure a suitable Caffeine cache, don't store null results and avoid a stampede.

Show solution

Note: with sync = true the unless attribute is not supported in some Spring versions. If startup fails, remove unless and make sure the method never returns null (throw an exception).

4. Project: measure before and after project

In the course project (order catalogue), apply Caffeine to ProductService.find and Redis to CategoryService.list. Make 100 consecutive requests with curl in a loop and compare the total time with and without the cache. Record the hit ratio in the Actuator. Keep the numbers: you will use them in session 3.

Session summary

The essentials in 10 points

  • Most of a web application's time is spent waiting for I/O, not calculating.
  • In parallel, the total time is that of the slowest task; in sequence, it is the sum.
  • CompletableFuture chains and combines asynchronous tasks without blocking.
  • Spring beans are singletons: no mutable fields; use local variables, Atomic* or immutable objects.
  • @Async works via a proxy: internal calls (this.) ignore it.
  • In ThreadPoolTaskExecutor, extra threads are only born when the queue is full.
  • spring.threads.virtual.enabled=true turns on virtual threads (Java 21+), ideal for I/O.
  • @Cacheable, @CachePut and @CacheEvict control the cache without tying the code to the technology.
  • Caffeine for a fast local cache; Redis for a cache shared between instances.
  • Always set a maximum size and a TTL, and measure the hit ratio.

Glossary

Thread
An independent thread of execution within a program.
Virtual thread
A lightweight thread managed by the JVM (Java 21+).
Thread pool
A group of reusable threads that execute tasks from a queue.
Race condition
A bug caused by threads accessing the same data at the same time.
Deadlock
Threads blocked forever waiting for each other.
Proxy
A middleman object that Spring places in front of your beans to apply annotations.
Cache
Fast storage of results so they can be reused.
Hit / Miss
Found / not found in the cache.
TTL
Time to live of a cache entry.
Eviction
Removal of entries from the cache.
Stampede
An avalanche of requests to the source when a popular entry expires.