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 Jetty2. After reading the source code of jetty for a while I came across SelectorManager with the following method.

private static int defaultSelectors(Executor executor)
{
	if (executor instanceof ThreadPool.SizedThreadPool)
	{
		int threads = ((ThreadPool.SizedThreadPool)executor).getMaxThreads();	
		int cpus = ProcessorUtils.availableProcessors();
		return Math.max(1, Math.min(cpus / 2, threads / 16));
	}
	return Math.max(1, ProcessorUtils.availableProcessors() / 2);
}

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

  1. https://stackoverflow.com/questions/18610381/why-does-jetty-establish-many-connections-when-it-starts-up

  2. https://www.eclipse.org/lists/jetty-users/msg04750.html

  3. https://jenkov.com/tutorials/java-nio/selectors.html

  4. https://jenkov.com/tutorials/java-nio/index.html

  5. https://stackoverflow.com/questions/25195128/how-do-jetty-and-other-containers-leverage-nio-while-sticking-to-the-servlet-spe

  6. https://github.com/eclipse/jetty.project/issues/1186#issuecomment-267772927