Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is maintaining a TCP socket in java

Tags:

java

tcp

I have currently implemented a heartbeat mechanism for my project and I am using TCP as my underlying connectivity. I was wondering how expensive is maintaining a tcp connection. Each slave sends a heartbeat every 5 seconds to the master(yes i know its way to often but i have a good reason to do so). So I was wondering should I constantly create a new connection or should I keep the connection open. Because if I keep the open connection then in that case I can just handle the exception. But since I need to know every 5 seconds wether or not a slave is down should I be re establishing the connection or just keep it open. Thanks in advance.

like image 969
Krish Avatar asked May 01 '16 21:05

Krish


People also ask

Is TCP connection expensive?

It's certainly more overhead than sending a UDP packet and not caring what happens past that. TCP also comes with more header data, and maintains the connection state, which will consume resources. So yes, compared to UDP, TCP is more expensive, but expensive is a relative term.

Is socket connection expensive?

Creating socket is cheap. Connecting it actually creates the connection, which is more or less as expensive as creating the underlying connection, specially TCP connection. TCP connection establish requires the three-way TCP handshake steps.

How long does a TCP socket stay open?

These sockets have no running timer by default - they will remain in that state forever, even if the communication is broken. The TCP stack will notice problems only when one side attempts to send something.


2 Answers

It's more expensive to re-open the connection regularly; there is a three-way handshake on open. Once the socket is open, that cost can be amortized (but only if you leave it open).

like image 163
Elliott Frisch Avatar answered Oct 04 '22 01:10

Elliott Frisch


As previously stated reopening the connection is more expensive, unless there are other factors involved like mobility. Not only do you have a three-way handshake, but you also have a four-way handshake terminating the connection. In addition to this, your TCP server application likely open up new threads for each new connection, which also needs to be allocated, deallocated etc. Most likely your connection will also pass through firewalls which are often NATed, which in turn opens up ports and states. This is why I personally rarely use UDP, because UDP may have problems passing through firewalls and ISP filters.

Finally the maintenance of the TCP connection itself from a protocol point of view is minimal. TCP do have the option of keep-alive, but these are rarely sent as often as every 5 seconds. There is a small overhead of context switching within your OS process, but that would happen regardless of you opening and closing the connection.

Keep it open.

like image 30
Andy Avatar answered Oct 04 '22 01:10

Andy