Project
Concurrent Market-Data Fetcher (CLI)
Goal: Build a command-line tool that fetches NSE stock quotes from several providers in parallel, compares three concurrency strategies with real timing, and routes each provider's outcome through a pattern-matching
switch— entirely offline. Time: ~6 hours · Uses: Parts 12–14
Project brief
A trading desk's screen shows one consolidated price per stock, even though that number is really the best of several data feeds answering at different speeds, some of which occasionally fail. This project builds a small, honest version of that: a watchlist of 12 NSE tickers, three simulated providers, fetched concurrently, with every provider's own outcome — a quote, an error, or a timeout — visible on request.
Everything runs offline. MarketDataServer is a local HttpServer on 127.0.0.1 backed by three plain CSV files under data/ — there is no real network call anywhere in this project.
A real run (the full script is in tests_manual.md):
$ java MarketFetcher --verbose fetch ZOMATO
Ticker Best Price Best Provider Responded Status
------------------------------------------------------------------
ZOMATO Rs.268.10 BSE-CROSS 2/3 PARTIAL
NSE-PRIMARY Rs. 268.45 112 ms
NSE-MIRROR TIMEOUT after 800 ms
BSE-CROSS Rs. 268.10 121 ms
$ java MarketFetcher benchmark
12 tickers, 3 providers each, timeout 800 ms
Strategy Seconds Speed-up
Sequential 3.01 1.0x
ExecutorService (4 threads) 1.20 2.5x
Virtual threads (1/ticker) 0.81 3.7x
same best prices every way: true
Files
| File | What it is |
|---|---|
README.md |
This brief and the step-by-step build guide |
Provider.java |
Enum: the three simulated providers (NSE-PRIMARY, NSE-MIRROR, BSE-CROSS) |
FetchOutcome.java |
sealed interface: what one provider gave back for one ticker |
Quote.java, ProviderError.java, ProviderTimeout.java |
The three (and only three) shapes a FetchOutcome can take |
TickerSnapshot.java |
One ticker's consolidated result: best price, best provider, every outcome |
Watchlist.java |
The 12 tickers this project knows about |
MarketFetcherException.java |
The one checked exception, for a command-line mistake |
MarketDataServer.java |
The offline stub: an HttpServer on 127.0.0.1, backed by data/*.csv |
MarketDataClient.java |
Fetches one ticker from all three providers with CompletableFuture |
WatchlistFetcher.java |
Three ways to fetch the whole watchlist: sequential, pooled, virtual threads |
MarketFetcher.java |
The command-line entry point (complete reference solution) |
data/*.csv |
Each provider's own price list — the "database" MarketDataServer serves from |
tests_manual.md |
Every command to try, with the exact expected output |
How to run
Open a terminal in this folder (JDK 21, see ../../TOOLING.md). No external jar, no build tool — this project only uses the JDK's own java.net.http client and com.sun.net.httpserver server:
javac -d out *.java
java -cp out MarketFetcher help
java -cp out MarketFetcher report
java -cp out MarketFetcher --verbose fetch ZOMATO YESBANK
java -cp out MarketFetcher benchmark
Run every command from this folder — data/ is read with a relative path, the same "wherever you run it from" rule Stage 1/2's projects used for their own data files.
| Option | What it does |
|---|---|
--timeout-ms N |
How long to wait for one provider before giving up (default 800) |
--verbose |
Show every provider's own outcome, not just the consolidated best price |
Features
| Command | What it does | Example |
|---|---|---|
fetch <ticker> [ticker...] |
Fetch one or more tickers right now | fetch RELIANCE TCS |
report |
Fetch the whole 12-ticker watchlist, one table (virtual threads) | report |
benchmark |
Fetch the whole watchlist 3 ways, compare real timing | benchmark |
help |
Show the command list and the watchlist | help |
A provider failing or timing out is not an error — fetch/report print PARTIAL/FAILED and keep going; that is this project's whole point. Only a command-line mistake prints Error: ... and exits non-zero:
| Bad input | Message | Exit |
|---|---|---|
fetch WIPRO (not on the watchlist) |
Error: Unknown ticker 'WIPRO'. Run 'java MarketFetcher help' to see the watchlist. |
1 |
fetch (no ticker given) |
Error: Usage: fetch <ticker> [ticker...] |
1 |
frobnicate |
Error: Unknown command 'frobnicate'. Run 'java MarketFetcher help' to see all commands. |
1 |
| (no command at all) | Error: a command is required. Run 'java MarketFetcher help' to see all commands. |
2 |
--timeout-ms abc report |
Error: --timeout-ms must be a whole number, got 'abc'. |
2 |
Architecture
you type a command
│
▼
┌───────────────────────────┐
│ MarketFetcher (CLI) │ reads args[], starts the stub, prints tables
└────────────┬──────────────┘
│ calls client.fetchTicker("ZOMATO") or WatchlistFetcher.fetchWithExecutor(...)
▼
┌───────────────────────────┐
│ MarketDataClient │ 3 concurrent CompletableFutures per ticker,
│ │ folded into one TickerSnapshot
└────────────┬──────────────┘
│ HTTP GET /quote/{provider}/{ticker}
▼
┌───────────────────────────┐
│ MarketDataServer │ HttpServer on 127.0.0.1, artificial latency,
│ │ backed by data/*.csv — no real network, ever
└───────────────────────────┘
WatchlistFetcher sits beside MarketDataClient, not inside it: it decides how many tickers run at once (sequential, a fixed pool, virtual threads); MarketDataClient always fans a single ticker's three providers out concurrently, no matter which strategy called it. The two concerns — how many tickers at once, how many providers per ticker — are independent, which is why WatchlistFetcher's three methods are so short.
Which Parts each piece uses
| Piece | Skills | Part |
|---|---|---|
MarketDataServer on 127.0.0.1 with artificial Thread.sleep latency |
the same offline local-server trick as Part 12's ParallelDownloader |
Part 12, section 7 |
MarketDataClient.fetchFromProvider: sendAsync(...).orTimeout(...).handle(...) |
CompletableFuture: async composition, timeouts, recovering instead of crashing |
Part 12, section 4 |
MarketDataClient.fetchTicker: CompletableFuture.allOf over 3 independent calls |
combining several async results that don't depend on each other | Part 12, section 4 |
WatchlistFetcher.fetchWithExecutor with a fixed pool |
ExecutorService, Callable/Future |
Part 12, section 3 |
WatchlistFetcher.fetchWithExecutor with Executors.newVirtualThreadPerTaskExecutor() |
virtual threads for I/O-bound work | Part 12, section 6 |
MarketFetcher.handleBenchmark: System.nanoTime(), three strategies timed and compared |
measure, don't guess, before trusting a "faster" claim | Part 13, section 6 |
MarketDataClient.buildSnapshot's bestPrice as a double accumulator, not a boxed running list |
avoiding needless autoboxing in a loop | Part 13, section 4 |
FetchOutcome as a sealed interface permits Quote, ProviderError, ProviderTimeout |
modelling a closed set of types | Part 14 |
MarketFetcher.formatOutcome: exhaustive pattern-matching switch, no default |
pattern matching for switch, record deconstruction, guarded patterns (when) |
Part 14 |
MarketDataClient.buildSnapshot: if (outcome instanceof Quote(...)) |
instanceof pattern matching to replace a cast |
Part 14 |
MarketFetcherException, arrow switch dispatch, exit codes |
same CLI/service split and error convention as the Stage 1 and Stage 2 projects | Stage 2 project |
Build it step by step
Build in small steps. Compile and run after every step. Try each one yourself before opening the finished .java files in this folder.
Step 1: Provider, the watchlist, and the sample data (Part 8 recap)
What and why: decide what you're fetching before deciding how. Three providers, each its own enum constant with a display name and a URL segment:
public enum Provider {
NSE_PRIMARY("NSE-PRIMARY", "nse-primary"),
NSE_MIRROR("NSE-MIRROR", "nse-mirror"),
BSE_CROSS("BSE-CROSS", "bse-cross");
private final String displayName;
private final String urlSegment;
// constructor, accessors, fromUrlSegment(String) lookup
}
Watchlist.TICKERS is a fixed List<String> of 12 NSE tickers. data/nse-primary.csv, data/nse-mirror.csv, data/bse-cross.csv each list TICKER,price for (almost) every ticker — with two deliberate gaps baked in, explained in Step 2.
✅ Test: Provider.fromUrlSegment("bse-cross") → Provider.BSE_CROSS.
Step 2: FetchOutcome — a sealed interface for "what happened" (Part 14)
What and why: a provider call can go three ways: a real quote, a provider-reported error ("no quote for this ticker"), or a timeout this client gave up waiting on. Modelling that as sealed tells the compiler — and everyone reading the code — that these three and only these three shapes exist.
public sealed interface FetchOutcome permits Quote, ProviderError, ProviderTimeout {
String ticker();
String provider();
}
public record Quote(String ticker, String provider, double price, long latencyMs) implements FetchOutcome {}
public record ProviderError(String ticker, String provider, String reason) implements FetchOutcome {}
public record ProviderTimeout(String ticker, String provider, long timeoutMs) implements FetchOutcome {}
Two gaps go into the sample data on purpose, so every run exercises every path with no randomness involved: data/bse-cross.csv has no row for YESBANK (→ a ProviderError), and (in Step 3) NSE-MIRROR is made to stall for 3 seconds on ZOMATO specifically (→ a ProviderTimeout).
✅ Test: new ProviderError("YESBANK", "BSE-CROSS", "no quote").ticker() → "YESBANK" — the interface's two accessor methods work on any of the three records, because every record's components happen to be named ticker/provider.
Step 3: MarketDataServer — the offline stub (Part 12, section 7)
What and why: this project fetches "from the network" the same way Part 12's ParallelDownloader did: a real HttpServer, started on an ephemeral local port, that nothing outside this machine can ever reach.
public String start() throws IOException {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/quote/", this::handleQuote);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.start();
return "http://127.0.0.1:" + server.getAddress().getPort();
}
Each provider's prices are loaded once from its CSV file into a Map<String, Double> at construction time — the server never touches the filesystem again per request, only pricesByProvider.get(provider).get(ticker). Every request sleeps for a fixed, provider-specific number of milliseconds before answering, standing in for real network latency: NSE-PRIMARY ~70ms, BSE-CROSS ~100ms, NSE-MIRROR ~190ms — except NSE-MIRROR on ZOMATO, which sleeps 3 seconds instead, on purpose.
✅ Test: start the server, curl http://127.0.0.1:PORT/quote/nse-primary/RELIANCE → RELIANCE,2456.75 after a short pause; curl .../quote/bse-cross/YESBANK → HTTP 404.
🔍 Going deeper:
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor())means the server itself handles every incoming request on its own virtual thread, so one slowZOMATOrequest sleeping for 3 seconds never blocks any other ticker's request from being answered at the same time — the server is exercising the exact same Part 12 idea this project's client side does.
Step 4: MarketDataClient — one ticker, three providers, one CompletableFuture (Part 12, section 4)
What and why: fetch all three providers for a ticker at once, not one after another, and never let one provider's failure take down the whole call.
public CompletableFuture<FetchOutcome> fetchFromProvider(String ticker, Provider provider) {
HttpRequest request = HttpRequest.newBuilder(
URI.create(baseUrl + "/quote/" + provider.urlSegment() + "/" + ticker)).build();
long startedAt = System.nanoTime();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.orTimeout(timeoutMs, TimeUnit.MILLISECONDS)
.handle((response, failure) -> {
long latencyMs = (System.nanoTime() - startedAt) / 1_000_000;
if (failure != null) {
return toOutcome(ticker, provider, failure); // TimeoutException -> ProviderTimeout, else ProviderError
}
if (response.statusCode() != 200) {
return new ProviderError(ticker, provider.displayName(), response.body());
}
double price = Double.parseDouble(response.body().split(",")[1]);
return new Quote(ticker, provider.displayName(), price, latencyMs);
});
}
.handle(...) (not .thenApply(...)) runs whether the call succeeded or failed, which is exactly what turns every outcome — success, timeout, or any other failure — into a plain FetchOutcome value instead of an exception that would need its own try/catch at every call site.
fetchTicker(ticker) then calls fetchFromProvider three times and joins them with CompletableFuture.allOf(...) — the three calls are already running concurrently the moment all three methods return, well before allOf is even reached.
✅ Test: client.fetchFromProvider("YESBANK", Provider.BSE_CROSS).join() → a ProviderError whose reason() contains "no quote".
🔍 Going deeper:
orTimeoutandsendAsyncboth report failures wrapped in aCompletionException—toOutcomeunwraps that withfailure.getCause()before checkinginstanceof TimeoutException, otherwise every timeout would be misread as "some other error."
Step 5: Picking the best price with instanceof pattern matching (Part 14)
What and why: fetchTicker has three FetchOutcomes and needs the lowest price among whichever ones are actually Quotes. Before Java 16, that meant a cast: if (outcome instanceof Quote) { Quote q = (Quote) outcome; ... }. A pattern variable skips the cast and names the fields directly:
for (FetchOutcome outcome : outcomes) {
if (outcome instanceof Quote(String quoteTicker, String provider, double price, long latencyMs)) {
responded++;
if (price < bestPrice) {
bestPrice = price;
bestProvider = provider;
}
}
}
This is a record pattern (Java 21): Quote(...) doesn't just check "is this a Quote?", it destructures the match into four local variables in one line. ProviderError and ProviderTimeout never match this if, so they are simply skipped — responded only counts providers that actually answered with a price.
✅ Test: feed buildSnapshot one Quote and one ProviderError → providersResponded == 1, bestPrice equals the Quote's price.
Step 6: Three ways to fetch a watchlist (Part 12, sections 3 and 6; Part 13)
What and why: fetchTicker already runs a ticker's three providers concurrently. The outer question — one ticker at a time, or many at once — is a separate decision, made by whoever calls WatchlistFetcher, not by MarketDataClient itself.
public static List<TickerSnapshot> fetchWithExecutor(List<String> tickers, MarketDataClient client,
ExecutorService pool) {
List<Future<TickerSnapshot>> futures = new ArrayList<>();
for (String ticker : tickers) {
futures.add(pool.submit(() -> client.fetchTicker(ticker).join()));
}
List<TickerSnapshot> results = new ArrayList<>();
for (Future<TickerSnapshot> future : futures) {
results.add(future.get()); // real code also catches ExecutionException/InterruptedException
}
return results;
}
The exact same method works for a small Executors.newFixedThreadPool(4) and Executors.newVirtualThreadPerTaskExecutor() — only the pool argument changes. fetchSequential is the same idea with no pool at all: one .join() per ticker, strictly in order.
✅ Test: WatchlistFetcher.fetchSequential(...) and fetchWithExecutor(..., Executors.newVirtualThreadPerTaskExecutor()) on the same watchlist return .equals() lists of best prices — only the wall-clock time differs.
🔍 Going deeper: why does
reportdefault to virtual threads, butbenchmarktries all three? Virtual threads are the right default for this kind of I/O-bound fan-out (Part 12, section 6) — but "the right default" is a conclusion from measuring, not a reason to skip measuring.benchmarkis this project's proof, not just its claim.
Step 7: Formatting outcomes with a pattern-matching switch (Part 14)
What and why: --verbose prints one line per provider. A switch over the sealed FetchOutcome, with record patterns and a guarded pattern for "this one was slow":
static String formatOutcome(FetchOutcome outcome) {
return switch (outcome) {
case Quote(String ticker, String provider, double price, long latencyMs) when latencyMs > SLOW_THRESHOLD_MS ->
String.format(" %-12s Rs.%,10.2f %5d ms (slow)", provider, price, latencyMs);
case Quote(String ticker, String provider, double price, long latencyMs) ->
String.format(" %-12s Rs.%,10.2f %5d ms", provider, price, latencyMs);
case ProviderError(String ticker, String provider, String reason) ->
String.format(" %-12s ERROR: %s", provider, reason);
case ProviderTimeout(String ticker, String provider, long timeoutMs) ->
String.format(" %-12s TIMEOUT after %d ms", provider, timeoutMs);
};
}
No default branch, and the compiler would refuse to compile this switch without one if it couldn't prove every case was covered — permits Quote, ProviderError, ProviderTimeout on FetchOutcome is exactly what lets it prove that. Delete one case and try compiling: the error names the exact type you forgot.
✅ Test: run --verbose fetch ZOMATO (see tests_manual.md) and confirm NSE-MIRROR prints as a TIMEOUT line, not a crash.
🔍 Going deeper: the
whenguard on the firstQuotecase is a guarded pattern — "matchQuote, and this extra condition." Without it, you would need a plainifinside the case body, which works but loses the one-line "which case is this" readability a guard keeps.
Step 8: MarketFetcher — the CLI and the benchmark (Stage 1/2 project pattern)
What and why: same shape as LibraryManager: parse global options, dispatch on the command name, one catch for MarketFetcherException. The one new idea is benchmark, which runs the exact same watchlist through all three WatchlistFetcher strategies and times each with System.nanoTime() (Part 13: measure, don't guess):
long start = System.nanoTime();
List<TickerSnapshot> sequential = WatchlistFetcher.fetchSequential(tickers, client);
double sequentialSeconds = (System.nanoTime() - start) / 1_000_000_000.0;
✅ Test: run every command and error case in tests_manual.md. Output and exit code must match exactly, except timing numbers, which are marked (varies).
🔍 Going deeper:
System.nanoTime(), notSystem.currentTimeMillis(), measures elapsed time here —nanoTimeis guaranteed monotonic (never runs backwards, even if the system clock is adjusted mid-measurement) and has no fixed relationship to wall-clock time at all; it only makes sense as a difference between two calls, which is exactly how every timing in this project uses it.
Stretch goals
- 🟢 A
--providersoption to query only some providers, e.g.--providers nse-primary,bse-cross. - 🟢 A
gainers/loserscommand: compare today'sdata/prices against a second "yesterday" CSV and rank the biggest movers. - 🟡 Retry a
ProviderTimeoutonce, with a shorter timeout, before giving up on that provider for good. - 🟡 Replace the fixed artificial latencies with a small, seeded random jitter — then decide how that changes what "reproducible output" means for
tests_manual.md. - 🔴 Package this project as a runnable JAR with a manifest
Main-Class, then as a Maven project — Part 15 walks through both, including a real verified Maven build. - 🔴 A
StructuredTaskScope(JEP 453/480 preview in 21, finalized later) version offetchTicker, for comparison with theCompletableFuture.allOfversion here.
Checklist
- I can start a local
HttpServeron an ephemeral port and treat it exactly like a real API in test/demo code. - I can compose independent async calls with
CompletableFuture.allOf, and turn failures into values with.handle(...)instead of letting them propagate as exceptions. - I can submit tasks to an
ExecutorServiceand collectFutureresults, and swap a fixed pool forExecutors.newVirtualThreadPerTaskExecutor()with no other code change. - I can measure two strategies with
System.nanoTime()before claiming one is faster. - I can model a closed set of outcomes with a
sealed interfaceand write an exhaustive pattern-matchingswitchwith record patterns and a guarded pattern, with nodefault. - I can replace an
instanceof+ cast with aninstanceofpattern that destructures a record directly. - Every command in
tests_manual.mdgives the expected output (timing lines aside) and exit code.
Next
🎉 Stage 3 done! Go back to the roadmap and get ready for Stage 4: DSA in Java.