Last active
February 4, 2025 01:28
-
-
Save unclebean/7d45a90b9441b6882c67b39524eff981 to your computer and use it in GitHub Desktop.
tomcat enable virtual thread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.catalina.connector.Connector; | |
import org.apache.coyote.ProtocolHandler; | |
import org.apache.coyote.http11.Http11NioProtocol; | |
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import java.util.concurrent.Executor; | |
import java.util.concurrent.Executors; | |
import java.util.logging.Logger; | |
@Configuration | |
public class TomcatConfig { | |
private static final Logger LOGGER = Logger.getLogger(TomcatConfig.class.getName()); | |
@Bean | |
public TomcatServletWebServerFactory tomcatFactory() { | |
return new TomcatServletWebServerFactory() { | |
@Override | |
protected void customizeConnector(Connector connector) { | |
ProtocolHandler protocolHandler = connector.getProtocolHandler(); | |
if (protocolHandler instanceof Http11NioProtocol http11NioProtocol) { | |
// Use Virtual Threads | |
Executor virtualThreadExecutor = Executors.newVirtualThreadPerTaskExecutor(); | |
http11NioProtocol.setExecutor(virtualThreadExecutor); | |
// Log confirmation | |
LOGGER.info("Tomcat is using Virtual Threads for request handling!"); | |
} | |
} | |
}; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.web.bind.annotation.GetMapping; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RestController; | |
@RestController | |
@RequestMapping("/test") | |
public class TestController { | |
@GetMapping("/thread") | |
public String checkThread() { | |
String threadName = Thread.currentThread().toString(); | |
System.out.println("Handling request in: " + threadName); | |
return "Current Thread: " + threadName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment