Wiring the service layer and handling many requests
50 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite already has services, DAOs and a connection pool from the console app. The web server must reuse them instead of copying the rules, and serve many customers at the same time without mixing their data.
Handlers call services, never DAOs: reusing the Section 13 layers
A handler is the HTTP layer of the app: it reads the request, calls one service method and writes the response. The service holds the business rules and the DAOs hold the SQL; a handler never calls a DAO directly.
Example 1 is a real ProductHandler: read the request, call the service, return a response.
Example 1 · src/main/java/com/shoplite/http/product/ProductHandler.java
Runs in: the shoplite-http project of this module (Maven, Jackson 3, HikariCP, MySQL)
package com.shoplite.http.product;
import com.shoplite.http.FieldErrors;import com.shoplite.http.JsonBody;import com.shoplite.http.PageParams;import com.shoplite.http.PageResponse;import com.shoplite.http.QueryParams;import com.shoplite.http.Request;import com.shoplite.http.Response;import com.shoplite.http.Router;import com.shoplite.http.product.ProductRequest.Mode;import com.shoplite.model.Page;import com.shoplite.model.Product;import com.shoplite.model.ProductFilter;import com.shoplite.model.ProductView;import com.shoplite.model.Sort;import com.shoplite.service.CatalogService;import java.math.BigDecimal;import java.util.List;
/** /api/v1/products: HTTP in, CatalogService call, HTTP out. No rules and no SQL here. */public final class ProductHandler {
private static final String ALL = "/api/v1/products"; private static final String ONE = "/api/v1/products/{id}"; private static final List<String> SORT_FIELDS = List.of("id", "name", "price", "stock"); private static final Sort DEFAULT_SORT = new Sort("id", true);
private final CatalogService catalog;
public ProductHandler(CatalogService catalog) { this.catalog = catalog; }
public void register(Router router) { router.get(ALL, this::list) .post(ALL, this::create) .get(ONE, this::get) .put(ONE, this::replace) .patch(ONE, this::patch) .delete(ONE, this::delete); }
private Response list(Request request) { QueryParams query = request.query(); FieldErrors errors = new FieldErrors(); ProductFilter filter = filter(query, errors); PageParams paging = PageParams.parse(query, SORT_FIELDS, DEFAULT_SORT, errors); errors.throwIfAny(); Page<ProductView> page = catalog.listProducts(filter, paging.page() + 1, paging.size(), paging.sort()); return Response.ok(PageResponse.of(page, ProductResponse::from)); }
private Response get(Request request) { return Response.ok(ProductResponse.from(catalog.findProductView(request.pathId("id")))); }
private Response create(Request request) { JsonBody body = request.body(); ProductRequest input = body.as(ProductRequest.class); input.validate(body, Mode.CREATE); Product saved = catalog.addProduct(input.toNewProduct()); return Response.created(request.locationOf(saved.id()), view(saved.id())); }
private Response replace(Request request) { return update(request, Mode.REPLACE); }
private Response patch(Request request) { return update(request, Mode.PATCH); }
private Response update(Request request, Mode mode) { JsonBody body = request.body(); ProductRequest input = body.as(ProductRequest.class); input.validate(body, mode); Product saved = catalog.updateProduct(request.pathId("id"), input.toChanges()); return Response.ok(view(saved.id())); }
private Response delete(Request request) { catalog.deleteProduct(request.pathId("id")); return Response.noContent(); }
/** The saved product read back with its category name, so responses always match GET. */ private ProductResponse view(int id) { return ProductResponse.from(catalog.findProductView(id)); }
private static ProductFilter filter(QueryParams query, FieldErrors errors) { String text = query.first("q").orElse(null); Integer categoryId = query.integer("categoryId", null, errors); BigDecimal minPrice = query.decimal("minPrice", errors); BigDecimal maxPrice = query.decimal("maxPrice", errors); boolean inStock = query.flag("inStock", errors); boolean includeInactive = query.flag("includeInactive", errors); if (minPrice != null && maxPrice != null && minPrice.compareTo(maxPrice) > 0) { errors.add("minPrice", "must not be greater than maxPrice"); } return new ProductFilter(text, categoryId, minPrice, maxPrice, inStock, includeInactive); }}$ curl -i -X POST http://localhost:8080/api/v1/products -H "Content-Type: application/json" -d '{"sku":"ACC-KB100","name":"Zebronics Wireless Keyboard","categoryId":4,"price":999.00,"stock":30}'
HTTP/1.1 201 Created
Date: Fri, 16 Oct 2026 06:26:53 GMT
Content-type: application/json
Content-length: 150
Location: http://localhost:8080/api/v1/products/16
What this code does
- Every method has the same three steps: read (path id, query or JSON body), call one
CatalogServicemethod, return aResponse. The handler has no SQL, no business rules and notry/catch: errors fly to the router'sErrorMapper. - The output is a real
curl -iPOST to this handler:createvalidated the body,addProductsaved it, and the handler answered201withLocation.
The call chain is Router → ProductHandler → CatalogService → ProductDao → MySQL, and each layer talks only to the one below it. If a handler called the DAO directly, the rules (a unique SKU, stock never below 0, an ordered product cannot be deleted) would live in two places, the console app and the HTTP server, and soon differ.
In shoplite-http, the model, dao, service and config packages come from shoplite-console. The new http package replaces the console app package; a few service methods were added for the API (PUT, PATCH, delete, filters), with the same design.
Order of execution
One request, layer by layer
Put the steps in the order a request travels.
Constructing the object graph by hand in a main class
The object graph is every object the app needs, connected through constructors: one pool, one Database, the DAOs, the services, the handlers and the router. Wiring means creating them once, in that order, in one place.
Example 2 is ShopLiteServer.start: it wires the graph in layer order and starts the server.
Example 2 · src/main/java/com/shoplite/http/ShopLiteServer.java
Runs in: the shoplite-http project of this module (Maven, Jackson 3, HikariCP, MySQL)
package com.shoplite.http;
import com.shoplite.config.AppConfig;import com.shoplite.config.DataSourceFactory;import com.shoplite.config.StartupException;import com.shoplite.dao.CategoryDao;import com.shoplite.dao.Database;import com.shoplite.dao.JdbcCategoryDao;import com.shoplite.dao.JdbcProductDao;import com.shoplite.dao.ProductDao;import com.shoplite.http.category.CategoryHandler;import com.shoplite.http.product.ProductHandler;import com.shoplite.service.CatalogService;import com.sun.net.httpserver.HttpServer;import com.zaxxer.hikari.HikariDataSource;import java.io.IOException;import java.net.BindException;import java.net.InetSocketAddress;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import javax.sql.DataSource;
/** Starts the ShopLite REST API: settings, pool, every object wired once, then the HTTP server. */public final class ShopLiteServer {
public static final String VERSION = "1.0.0";
private final HttpServer server; private final ExecutorService workers;
private ShopLiteServer(HttpServer server, ExecutorService workers) { this.server = server; this.workers = workers; }
public static void main(String[] args) { try { AppConfig config = AppConfig.load(); ServerSettings settings = ServerSettings.fromEnv(System.getenv()); HikariDataSource dataSource = DataSourceFactory.create(config); ShopLiteServer app = start(settings, dataSource); Runtime.getRuntime().addShutdownHook(new Thread(() -> { app.stop(); dataSource.close(); System.out.println("ShopLite API stopped."); })); System.out.println("ShopLite API " + VERSION + " on http://localhost:" + app.port() + "/api/v1 (" + settings.threads() + " threads, pool size " + config.poolSize() + ")"); } catch (StartupException e) { System.err.println("ShopLite could not start: " + e.getMessage()); System.exit(1); } }
/** Wires dao -> service -> handlers -> router and starts listening. Tests pass port 0 for a free port. */ public static ShopLiteServer start(ServerSettings settings, DataSource dataSource) { Database db = new Database(dataSource); CategoryDao categoryDao = new JdbcCategoryDao(db); ProductDao productDao = new JdbcProductDao(db);
CatalogService catalog = new CatalogService(categoryDao, productDao);
Router router = new Router(new ErrorMapper()); new CategoryHandler(catalog).register(router); new ProductHandler(catalog).register(router);
HttpServer server; try { server = HttpServer.create(new InetSocketAddress(settings.port()), 0); } catch (BindException e) { throw new StartupException("Port " + settings.port() + " is already in use. Stop the other program" + " or set SERVER_PORT to a free port.", e); } catch (IOException e) { throw new StartupException("Cannot open port " + settings.port() + ": " + e.getMessage(), e); } server.createContext("/", router); ExecutorService workers = Executors.newFixedThreadPool(settings.threads()); server.setExecutor(workers); server.start(); return new ShopLiteServer(server, workers); }
public int port() { return server.getAddress().getPort(); }
/** Stops taking new requests, lets running ones finish (at most 5 seconds), then ends the threads. */ public void stop() { server.stop(5); workers.shutdown(); try { if (!workers.awaitTermination(5, TimeUnit.SECONDS)) { workers.shutdownNow(); } } catch (InterruptedException e) { workers.shutdownNow(); Thread.currentThread().interrupt(); } }}$ java -jar target/shoplite-http-1.0.0.jar ShopLite API 1.0.0 on http://localhost:8080/api/v1 (16 threads, pool size 5)
What this code does
startwires the graph in layer order:Database→ DAOs →CatalogService→ handlers →Router. Each object is created once and passed on through constructors, so every request shares the same service and pool.- The server gets a fixed pool of
settings.threads()workers beforestart(). A taken port becomes aStartupExceptionwith the fix in its message, and the shutdown hook stops the server, then closes the pool.
Each class receives what it needs through its constructor (constructor injection) and never creates it itself. That is why the Section 13 service tests could pass in-memory DAOs, and why this server can reuse the services unchanged.
Without one place for the wiring, a handler that calls new CatalogService(new JdbcProductDao(...)) for each request creates new objects every time, or even a new pool, and quickly runs out of database connections.
The default single thread versus an executor (virtual threads on Java 21)
An executor is the set of threads that run your handlers. By default (setExecutor(null)) the JDK server runs every handler on one thread, one request after another; a thread pool lets requests run at the same time.
Example 3 sends five requests together to the default executor and to a pool of 8 threads. Example 4 uses virtual threads.
Example 3 · Default single thread versus a pool
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.util.ArrayList;import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
public class ExecutorDemo {
/** Sends 5 requests at once to a slow handler and reports how many were inside the handler together. */ static int maxAtOnce(ExecutorService workers) throws IOException { CountDownLatch allArrived = new CountDownLatch(5); AtomicInteger running = new AtomicInteger(); AtomicInteger max = new AtomicInteger(); HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/reports/slow", exchange -> { max.accumulateAndGet(running.incrementAndGet(), Math::max); allArrived.countDown(); try { allArrived.await(200, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } running.decrementAndGet(); exchange.sendResponseHeaders(204, -1); exchange.close(); }); server.setExecutor(workers); server.start();
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/reports/slow"); HttpClient client = HttpClient.newHttpClient(); List<CompletableFuture<HttpResponse<Void>>> calls = new ArrayList<>(); for (int i = 0; i < 5; i++) { calls.add(client.sendAsync(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.discarding())); } calls.forEach(CompletableFuture::join); server.stop(0); if (workers != null) { workers.shutdown(); } return max.get(); }
public static void main(String[] args) throws IOException { System.out.println("default (no executor): at most " + maxAtOnce(null) + " request(s) at a time"); System.out.println("fixed pool of 8: at most " + maxAtOnce(Executors.newFixedThreadPool(8)) + " request(s) at a time"); }}default (no executor): at most 1 request(s) at a time fixed pool of 8: at most 5 request(s) at a time
What this code does
- Five requests arrive together. The handler waits briefly for the others, like a slow query. With the default executor only one handler runs at a time, so the others queue behind it.
- With
newFixedThreadPool(8)all five run together.setExecutormust be called beforestart(); the pool is shut down after the server stops.
Example 4 · Java 21: one virtual thread per request
// Java 21import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.util.ArrayList;import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicInteger;
public class VirtualThreadsDemo {
/** Sends 5 requests at once to a slow handler and reports how many were inside the handler together. */ static int maxAtOnce(ExecutorService workers) throws IOException { CountDownLatch allArrived = new CountDownLatch(5); AtomicInteger running = new AtomicInteger(); AtomicInteger max = new AtomicInteger(); AtomicBoolean onVirtual = new AtomicBoolean(); HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/reports/slow", exchange -> { max.accumulateAndGet(running.incrementAndGet(), Math::max); onVirtual.set(Thread.currentThread().isVirtual()); allArrived.countDown(); try { allArrived.await(200, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } running.decrementAndGet(); exchange.sendResponseHeaders(204, -1); exchange.close(); }); server.setExecutor(workers); server.start();
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/reports/slow"); HttpClient client = HttpClient.newHttpClient(); List<CompletableFuture<HttpResponse<Void>>> calls = new ArrayList<>(); for (int i = 0; i < 5; i++) { calls.add(client.sendAsync(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.discarding())); } calls.forEach(CompletableFuture::join); server.stop(0); if (workers != null) { workers.shutdown(); } System.out.println(" handler ran on a virtual thread: " + onVirtual.get()); return max.get(); }
public static void main(String[] args) throws IOException { // one cheap virtual thread per request: no pool size to choose System.out.println("virtual threads: at most " + maxAtOnce(Executors.newVirtualThreadPerTaskExecutor()) + " request(s) at a time"); }}handler ran on a virtual thread: true virtual threads: at most 5 request(s) at a time
What this code does
newVirtualThreadPerTaskExecutor()starts a new virtual thread for every request, so there is no pool size to tune;isVirtual()confirms where the handler ran.- The handler code does not change at all. Virtual threads help most when requests mostly wait (for MySQL or another API), which is typical for a REST server.
server.setExecutor(Executors.newFixedThreadPool(16)), called before start(), gives the server 16 worker threads. ShopLite reads the number from SERVER_THREADS. Too few threads and requests queue; too many and they only wait for the database instead.
On Java 21, Executors.newVirtualThreadPerTaskExecutor() gives each request its own virtual thread, a very cheap thread managed by the JVM, so thousands of waiting requests cost little memory. ShopLite stays on Java 17, so it uses the fixed pool; the change is one line when you move to 21.
Predict the output
How many handlers run at once?
Five slow requests arrive together. Pick how many handlers run at the same time.
Round 1 of 2
How many handlers run at the same time?
Thread safety: shared services and the DataSource pool
A stateless service keeps no request data in its fields: they are only final references to DAOs, and everything about one request lives in local variables and parameters. One such object can serve many threads at once.
Example 5 shows what goes wrong when a shared object has a mutable field.
Example 5 · Mistake: a mutable field in a shared service
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.util.ArrayList;import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;
/** A "service" with a mutable field: every request thread shares the same object. */class VisitStats { private int plainCount; private final AtomicInteger safeCount = new AtomicInteger();
void recordVisit() { plainCount++; safeCount.incrementAndGet(); }
String report() { return "plain int: " + plainCount + ", AtomicInteger: " + safeCount.get(); }}
public class SharedStateDemo { public static void main(String[] args) throws IOException { VisitStats stats = new VisitStats(); HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/fest/visit", exchange -> { for (int i = 0; i < 1000; i++) { stats.recordVisit(); } exchange.sendResponseHeaders(204, -1); exchange.close(); }); ExecutorService workers = Executors.newFixedThreadPool(8); server.setExecutor(workers); server.start();
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/fest/visit"); HttpClient client = HttpClient.newHttpClient(); List<CompletableFuture<HttpResponse<Void>>> calls = new ArrayList<>(); for (int i = 0; i < 50; i++) { calls.add(client.sendAsync(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.discarding())); } calls.forEach(CompletableFuture::join); System.out.println("expected 50000 visits"); System.out.println(stats.report()); server.stop(0); workers.shutdown(); }}expected 50000 visits plain int: 47922, AtomicInteger: 50000
What this code does
- Eight pool threads update the same
VisitStatsobject.plainCount++loses updates when two threads read the same old value, so the total is short; the number changes on every run. AtomicInteger.incrementAndGet()does the read-add-write as one step and always reaches 50000. ShopLite services avoid the problem completely by keeping no request data in fields.
With a pool of threads, one CatalogService object serves many requests at the same time. A mutable field, such as a counter or a "last search" field, is shared by every thread and gives wrong results: count++ on a shared int loses updates when two threads run it together, because it is three steps (read, add, write). Use AtomicInteger, or better, keep no such state in services at all.
The HikariCP DataSource is built for threads: each request borrows its own connection and gives it back. ShopLite's Database keeps a transaction's connection in a ThreadLocal, so each request thread sees only its own. Keep the pool size close to what MySQL can handle (ShopLite uses 5 to 10); extra HTTP threads simply wait up to 5 seconds for a free connection.
Find the bug
Find the shared state
Click the line that is not safe when many requests run together.
Which line loses updates under load?
Round 1 of 2Graceful stop and configuration from environment variables
A graceful stop finishes the work in progress before the program ends: server.stop(5) stops accepting new connections and waits up to 5 seconds for running requests, then the worker threads are shut down and the connection pool is closed last.
Example 6 stops the server while an order request is half-way and still delivers its answer.
Example 6 · stop(seconds) lets a running request finish
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.util.concurrent.CompletableFuture;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class GracefulStopDemo { public static void main(String[] args) throws Exception { CountDownLatch started = new CountDownLatch(1); HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/orders", exchange -> { started.countDown(); try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } byte[] body = "order 17 placed".getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(201, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); ExecutorService workers = Executors.newFixedThreadPool(4); server.setExecutor(workers); server.start();
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/orders"); HttpClient client = HttpClient.newHttpClient(); CompletableFuture<HttpResponse<String>> inFlight = client.sendAsync( HttpRequest.newBuilder(uri).POST(HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.ofString()); started.await();
System.out.println("stopping: no new connections, wait up to 3 s for running requests"); server.stop(3); workers.shutdown(); workers.awaitTermination(3, TimeUnit.SECONDS); HttpResponse<String> r = inFlight.join(); System.out.println("in-flight request finished: " + r.statusCode() + " " + r.body());
try { client.send(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofString()); } catch (IOException e) { System.out.println("new request after stop: " + e.getClass().getSimpleName()); } }}stopping: no new connections, wait up to 3 s for running requests in-flight request finished: 201 order 17 placed new request after stop: ConnectException
What this code does
- An order request is half-way when
stop(3)is called. The server stops accepting connections but waits for the running exchange, so the client still gets201. - After the stop, a new request cannot connect at all (
ConnectException). ShopLite runs the same steps from a shutdown hook: stop the server, finish the workers, close the pool last.
A shutdown hook (Runtime.getRuntime().addShutdownHook(thread)) runs these steps when the user presses Ctrl+C. Without it, Ctrl+C can cut an order in the middle of its response, and open connections are dropped instead of closed. MySQL rolls back an unfinished transaction, but the customer never learns whether the order went through.
Settings come from environment variables, not from the code: DB_URL, DB_USER and DB_PASSWORD as in Section 13, plus SERVER_PORT (default 8080) and SERVER_THREADS (default 16). Each value is checked at startup, so a typo stops the server with a clear message instead of failing on the first request.
Next step
Check your understanding
12 quick questions