Why the Spring Boot controller can't handle other requests if Thread.sleep is used?

Viewed 449

When we use the Thread.sleep(...) method in the Spring Boot controller, we cannot accept requests concurrently. All requests can only be processed one by one. Why not every request is processed in parallel?

For example, there is a Thread.sleep(...) in the sleep method. In order to simulate the parallel access to the sleep method, I used the Chrome browser to open multiple tabs to visit http://localhost:8080/async. Observe that multiple tabs are executed in series. Why is it not executed in parallel here?

@RestController
public class AsyncController {

    @RequestMapping("async")
    public String sleep() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        System.out.println("[before]name is " + Thread.currentThread().getName() + " time is " + startTime);
        Thread.sleep(10000);
        long endTime = System.currentTimeMillis();
        System.out.println("[after]name is " + Thread.currentThread().getName() + " time is " + endTime + " cos " + (endTime-startTime));
        return Thread.currentThread().getName();
    }

}

Console printing

[before]name is http-nio-8080-exec-2 time is 1602751326997
[after]name is http-nio-8080-exec-2 time is 1602751337000 cos 10003
[before]name is http-nio-8080-exec-3 time is 1602751337004
[after]name is http-nio-8080-exec-3 time is 1602751347008 cos 10004
0 Answers
Related