As we saw in the last tutorial that Spring controller's handler method can process Servlet 3 based asynchronous request processing by returning an instance of Callable.
Another option is for the controller method to return an instance of org.springframework.web.context.request.async.DeferredResult.
Callable vs DeferredResult
A Callable returned from a handler method, is processed asynchronously by the Spring container. In contrast, a DeferredResult allows the application to produce the return value from a thread of its own choosing (e.g., in response to an external event like a JMS message or a scheduled task). The developer is responsible for all thread management.
Example
Let's rewrite our previous example to see how that works.
Creating the Controller
package com.logicbig.example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;
import java.time.LocalTime;
@Controller
public class MyController {
@GetMapping("test")
@ResponseBody
public DeferredResult<String> handleTestRequest() {
log("handler started");
final DeferredResult<String> deferredResult = new DeferredResult<>();
new Thread(() -> {
log("async task started");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log("async task finished");
deferredResult.setResult("test async result");
}).start();
log("handler finished");
return deferredResult;
}
private static void log(String msg) {
System.out.println(
LocalTime.now() +
" MyController [" +
Thread.currentThread().getName() + "] "
+ msg);
}
}
The Integration test
package com.logicbig.example;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.test.web.servlet.assertj.MvcTestResult;
import org.springframework.web.context.WebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
@SpringJUnitWebConfig(MyWebConfig.class)
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvcTester mockMvcTester;
@BeforeEach
public void setup() {
this.mockMvcTester = MockMvcTester.from(this.wac);
}
@Test
public void testController() {
MvcTestResult result = mockMvcTester.get()
.uri("/test")
.asyncExchange();
assertThat(result).request().hasAsyncStarted(true);
assertThat((String) result.getMvcResult().getAsyncResult())
.isEqualTo("test async result");
}
}
mvn clean test -Dtest="ControllerTest" Output$ mvn clean test -Dtest="ControllerTest" [INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for com.logicbig.example:spring-async-deferredresult-example:war:1.0-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-war-plugin is missing. @ line 37, column 21 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] ------< com.logicbig.example:spring-async-deferredresult-example >------ [INFO] Building spring-async-deferredresult-example 1.0-SNAPSHOT [INFO] from pom.xml [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- clean:3.2.0:clean (default-clean) @ spring-async-deferredresult-example --- [INFO] Deleting D:\example-projects\spring-mvc\spring-async-deferredresult-example\target [INFO] [INFO] --- resources:3.3.1:resources (default-resources) @ spring-async-deferredresult-example --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-async-deferredresult-example\src\main\resources [INFO] [INFO] --- compiler:3.3:compile (default-compile) @ spring-async-deferredresult-example --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 2 source files to D:\example-projects\spring-mvc\spring-async-deferredresult-example\target\classes [INFO] [INFO] --- resources:3.3.1:testResources (default-testResources) @ spring-async-deferredresult-example --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-async-deferredresult-example\src\test\resources [INFO] [INFO] --- compiler:3.3:testCompile (default-testCompile) @ spring-async-deferredresult-example --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to D:\example-projects\spring-mvc\spring-async-deferredresult-example\target\test-classes [INFO] [INFO] --- surefire:3.2.5:test (default-test) @ spring-async-deferredresult-example --- [INFO] Using auto detected provider org.apache.maven.surefire.junit4.JUnit4Provider [WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.logicbig.example.ControllerTest 11:11:24.245 MyController [main] handler started 11:11:24.249 MyController [main] handler finished 11:11:24.261 MyController [Thread-3] async task started 11:11:26.267 MyController [Thread-3] async task finished [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.140 s -- in com.logicbig.example.ControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 6.248 s [INFO] Finished at: 2026-08-16T11:11:26+08:00 [INFO] ------------------------------------------------------------------------
In what scenarios we should prefer DeferredResult over Callable
DeferredResult is a better choice if we want to use an entirely decoupled code for processing, e.g. putting some information in a queue which is being polled by some other thread.
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 3.2.9.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- spring-test 7.0.6 (Spring TestContext Framework)
- junit-jupiter-engine 6.0.3 (Module "junit-jupiter-engine" of JUnit)
- hamcrest 3.0 (Core API and libraries of hamcrest matcher framework)
- assertj-core 3.26.3 (Rich and fluent assertions for testing in Java)
- JDK 25
- Maven 3.9.11
|