'Spring controller's method could be blocked by sleep method call?
weird problem.I just wrote one controller like below: enter image description here
Then i requested the api twice at the same time on my browser, but i found that one of the apis which is requested at the previous time blocked the other one?We could see the result like below:
**get locktime:Thu May 12 10:32:00 CST 2022current thread:http-nio-1111-exec-1:70**
**get locktime:Thu May 12 10:32:20 CST 2022current thread:http-nio-1111-exec-1:70**
diff seconds is 20 ?why weren't they print at the same time?
package com.shopping.redisson.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.concurrent.TimeUnit;
@RestController
public class TestTController {
@GetMapping("/test222")
public String testT() throws InterruptedException {
System.out.println("get locktime:"+(new Date()).toString()+"current thread:"+Thread.currentThread().getName()+":"+Thread.currentThread().getId());
TimeUnit.SECONDS.sleep(20);
return (new Date()).toString();
}
}
Solution 1:[1]
Unless specified all Beans in Spring are singleton meaning only one instance is available for serving your requests. RestController is also be one of bean.
Since you have only one instance & as soon as you hit your controller method, there is 20 seconds delay to complete that execution.
That is reason even after you hit multiple requests at same time, other requests only got served after 20 seconds.
Reference https://docs.spring.io/spring-framework/docs/3.0.0.M4/reference/html/ch03s05.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashish Patil |
