Jetty was establishing a bunch of tcp connections to itself on start of the application. I have tried searching for this but didn’t come up with anything solid.
So I fired up wireshark to analyze the TCP packets. There were total of 12 ports utilized for 6 sockets. Started monitoring the loopback interface with the following filter.
tcp.port in {<comma separated ports>}
At this point the server was idle and nothing was hapenning on these ports either. So to test what would happen if I initiated a request to the server, I started connecting to the server using curl in a inifinite loop. The moment I initiated these requests, I started seeing some packets in my wireshark console. I then terminated the while loop and started looking at the TCP packets. I was expecting something that could give some hint on why these tcp connections are established in the first place. But there was just 1 byte of data being sent in those packets and the data itself was 01(in hex).
Then I stumbled upon an answer from stackoverflow1
The Answer talks about selectors and after a little bit of googling I ended up at a thread about “understanding selector threads in Jetty”2. After reading the source code of jetty for a while I came across SelectorManager
with the following method.
If I go by the above logic, 6 selectors makes sense in my case. To futher confirm that selectors are the ones establishing those tcp connections I have setup some breakpoints.
With more exploration I understood that Jetty selectors are basically based on NIO selectors3. Now NIO is a Non-Blocking IO API that java offers4. Jetty leverages NIO to handle multiple channels with fewer threads5.
From jetty 9+ the only connector that it offers is the ServerConnector
which is based on NIO6.
Footnotes
-
https://stackoverflow.com/questions/18610381/why-does-jetty-establish-many-connections-when-it-starts-up ↩
-
https://stackoverflow.com/questions/25195128/how-do-jetty-and-other-containers-leverage-nio-while-sticking-to-the-servlet-spe ↩
-
https://github.com/eclipse/jetty.project/issues/1186#issuecomment-267772927 ↩