240. Implementing an HTTP web server on top of virtual threads
Implementing a simple HTTP web server in Java is quite easy since we already have an API ready to guide and serve our goals. We start from the HttpServer
class (this class is present in the com.sun.net.httpserver
package), which allows us to achieve our goal straightforwardly in a few steps.
Before jumping into the code, let’s quickly mention that our web server will allow us to choose between platform and virtual threads and between non-locking or locking (for instance, to simulate access to a database). We will make these choices via two boolean parameters of our startWebServer(boolean virtual, boolean withLock)
method, named virtual
and withLock
, respectively. So, we will have four possible configurations.
First, we create an HttpServer
via the create()
method. At this point, we also set up the port of our web server:
private static final int MAX_NR_OF_THREADS = 200;
private static final int WEBSERVER_PORT...