Scrivio Interview library
DebuggingIntermediate8 min read · updated 12 November 2026

A JAX-RS resource injects UriInfo with @Context and passes it to a CompletableFuture running on a separate executor. Under load, some responses contain links with another user's request path. Explain the cause and the fix.

The injected UriInfo is not a plain object but a proxy that finds the current request through state bound to the request thread. On an executor thread that state belongs to whatever request that thread last served, or to none, so the links are built from another user's request. The fix is to read the values we need on the request thread, pass those plain values to the async task, and tell the runtime the request is still in progress with AsyncResponse or a CompletionStage return type.

Why this question is asked

This is a bug that never shows up in a developer's single request and only appears in production under load, where it can expose one user's data to another. Interviewers like it because the answer needs three pieces of understanding at once: how JAX-RS injects request objects, how thread-local state works, and how asynchronous request processing works. In this answer, we will recap what the injected UriInfo really is, reproduce the bug, walk through why the wrong request is seen, fix it by capturing values early and using the async API correctly, apply the same rule to SecurityContext and MDC, and write a test that would have caught it.

1A Quick Recap: What Is Injected Into the Field?

UriInfo is the JAX-RS object that describes the request URI: the base URI, the path, the path and query parameters, and builders for new links. We usually get it with @Context, either as a field or as a method parameter.

What we receive is rarely the request's real UriInfo object. Implementations such as Jersey and RESTEasy give us a proxy, a generated object that implements UriInfo and forwards each call to the real object for the current request. To know what the current request is, the proxy uses state bound to the thread that is processing it, usually a ThreadLocal, a variable where each thread sees its own value. The request thread is set up before our method runs and cleaned up, or reused, after the request finishes.

2Reproducing the Problem

Here is a resource that computes an order summary on a separate executor and builds a self link inside the task.

Java
@Path("/orders")
public class OrderResource {
@Context UriInfo uriInfo; // a request-bound proxy
@Inject ExecutorService pool;
@GET @Path("/{id}/summary")
public CompletionStage<Summary> summary(@PathParam("id") long id) {
return CompletableFuture.supplyAsync(() -> {
Summary s = service.compute(id);
// BROKEN: runs on a pool thread, not the request thread
s.self = uriInfo.getAbsolutePathBuilder().build(); // /orders/91/summary, not /orders/42/summary
return s;
}, pool);
}
}

In a test with one request, this usually works, or fails with an exception about no request scope, depending on the implementation. Under load, some responses contain links with another user's path. The data is correct; only the link is wrong. That is the clue that points away from the service and toward the request objects.

3Why the Task Sees Another Request

The lambda captures the proxy, not the request's data. When the pool thread calls uriInfo.getAbsolutePathBuilder(), the proxy asks its thread-bound state which request is current. The pool thread is not the request thread, so one of three things happens. If the pool thread has no request bound, the call fails. If the runtime propagated context in some way, it may work. And if the pool happens to share threads with request processing, or a stale value was left on the thread, the proxy resolves to a different request, which is exactly what we see under load.

There is a second, independent problem. Even with the right request object, the original request may already be finished by the time the task runs if the runtime does not know the response is pending. Request objects can then be recycled for the next request on that connection. So the fix has to address both: which thread reads the request data, and how long the request is kept open.

Step throughTwo requests, one pool thread
Request thread APool threadUriInfo proxyRequest thread B
submit task for /orders/42
returns; request A waits for the task
request B binds /orders/91 to its context
getAbsolutePathBuilder()
resolves current request: /orders/91
summary for 42 with a link to 91

6 messages in order. Play them, or step through them one at a time.

The proxy answers for whatever request it can find, not for the request that started the task.

4Fix 1: Capture Plain Values on the Request Thread

The first and most important change is to read everything we need from request objects before starting the asynchronous work. A URI, a String or a long is a plain immutable value, so it is safe to share with any thread.

Java
@GET @Path("/{id}/summary")
public CompletionStage<Summary> summary(@PathParam("id") long id,
@Context UriInfo uriInfo) {
URI self = uriInfo.getAbsolutePath(); // read now, on the request thread
URI base = uriInfo.getBaseUri(); // http://host/api/
return CompletableFuture.supplyAsync(() -> {
Summary s = service.compute(id);
s.self = self; // /orders/42/summary, always
s.invoice = UriBuilder.fromUri(base).path("invoices/{id}").build(id);
return s;
}, pool);
}

Notice that the lambda now captures self and base, which are ordinary URI objects, and never touches the proxy. UriBuilder.fromUri builds new links from the captured base without needing any request context. Moving the UriInfo to a method parameter also makes it obvious that it belongs to this call.

5Fix 2: Tell the Runtime the Request Is Still Running

JAX-RS has two supported ways to finish a response later. Returning a CompletionStage, as above, lets the runtime suspend the request and write the response when the stage completes. The older style is an @Suspended AsyncResponse parameter, which we resume when the work is done. Both keep the request open, apply timeouts we configure, and make sure the response is written once.

Java
@GET @Path("/{id}/summary")
public void summary(@PathParam("id") long id, @Context UriInfo uriInfo,
@Suspended AsyncResponse async) {
URI self = uriInfo.getAbsolutePath(); // captured first
async.setTimeout(5, TimeUnit.SECONDS);
pool.submit(() -> {
try {
async.resume(service.compute(id).withSelf(self)); // 200 with the right link
} catch (Exception e) {
async.resume(e); // mapped by ExceptionMappers
}
});
}

What we must not do is start a background task from an ordinary synchronous method and return immediately, or block a request thread on future.get() from a fire-and-forget task. The first lets the request end while work still refers to it; the second wastes the request thread and hides the async design.

6The Same Rule for SecurityContext and MDC

Every request-bound object has the same problem. SecurityContext is also a proxy, so read the principal name and the roles we need on the request thread and pass them as values. The logging MDC, the mapped diagnostic context that adds fields such as a request id to every log line, is a ThreadLocal map too. A pool thread does not have the request's MDC, or has a stale one from earlier work, so log lines get the wrong request id.

The pattern is the same: copy explicitly, do not hold the proxy. Take a copy with MDC.getCopyOfContextMap() on the request thread, set it at the start of the task, and clear it in a finally block. Many teams wrap their executor so every submitted task does this automatically. Tracing libraries such as OpenTelemetry provide context-propagating executors for the same purpose.

Java
String user = securityContext.getUserPrincipal().getName(); // "alice", read now
Map<String, String> mdc = MDC.getCopyOfContextMap(); // {requestId=7f3a}
pool.submit(() -> {
if (mdc != null) MDC.setContextMap(mdc);
try { audit.record(user, id); } // logs requestId=7f3a
finally { MDC.clear(); } // nothing left for the next task
});

7Proving the Fix With a Concurrent Test

Because the bug only appears with overlapping requests, a test with one request proves nothing. The useful test sends many requests in parallel, each for a different id, and checks that every response links to its own id.

Java
@Test
void linksBelongToTheirOwnRequest() throws Exception {
HttpClient client = HttpClient.newHttpClient();
List<CompletableFuture<Boolean>> checks = IntStream.range(0, 500).mapToObj(i ->
client.sendAsync(get("/orders/" + i + "/summary"), ofString())
.thenApply(r -> r.body().contains("/orders/" + i + "/summary"))).toList();
long wrong = checks.stream().map(CompletableFuture::join).filter(ok -> !ok).count();
assertEquals(0, wrong); // before the fix: a handful of wrong links; after: 0
}

Run it against the real server with a small executor so threads are reused often. Before the fix it fails intermittently, which is the honest picture of the production bug; after the fix it passes every time.

8Follow-up questions

Why did the bug not show up in development?

With one request at a time, there is no other request for the proxy to resolve to. Either the call fails clearly, or the thread-bound state still happens to point at the only request. Data from another user can only appear when two requests overlap and threads are reused, which is the normal situation under load.

Can the runtime propagate the context to my executor for me?

Some environments can. Jakarta Concurrency's ManagedExecutorService and implementation-specific features can propagate certain contexts to tasks, and MicroProfile Context Propagation does the same in some runtimes. It is worth using when available, but whether UriInfo itself is propagated varies, so check your version. Capturing plain values is portable and always correct.

Is it safe to store the URI object itself rather than a String?

Yes. java.net.URI is immutable, so sharing it between threads is safe. What is unsafe is holding a reference to a request-bound object such as the UriInfo proxy, SecurityContext, HttpHeaders or a servlet request, because what they return depends on which thread calls them and when.

9Conclusion

In this answer, we saw that the UriInfo injected with @Context is a proxy bound to the request thread, so calling it from a CompletableFuture on another executor can resolve to a different request or fail. We fixed it by reading the base URI, path and parameters on the request thread and passing those plain values to the task, and by using a CompletionStage return type or AsyncResponse so the runtime keeps the request open. We applied the same rule to SecurityContext and MDC, and we wrote a parallel test that checks every returned link.

What to say in the interviewAbout 90 seconds aloud

Open with

The UriInfo we get from @Context is not a plain value object. It is a proxy, and on each call it finds the current request through state bound to the request thread, usually a thread local.

Then, if they want more

When the resource hands it to a CompletableFuture on a separate executor, the call runs on a pool thread. That thread either has no request bound, so the call fails, or it has some other request's state, so the link is built from another user's path. That is why it only shows up under load.

The fix is to capture what we need on the request thread before going async: the absolute path, the base URI, the path parameters, as plain URI and String values, and then build links in the task with UriBuilder from those values.

I also make sure the method returns a CompletionStage or uses an @Suspended AsyncResponse, so the runtime knows the request is still in progress and does not recycle it. I apply the same rule to SecurityContext and to the logging MDC: copy the principal name and the MDC map explicitly and set and clear them in the task.

Finally I would add a test that fires a few hundred parallel requests with different ids and asserts every link matches its own id, because a single-request test cannot catch this.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A JAX-RS resource injects UriInfo with @Context and passes it to a CompletableFuture...": https://scrivio-interview-library.netlify.app/java/jax-rs/206c6563d2/