2

I created a server socket on my side. I don't know when client connects to me.

Calling a serverSocket.accept() in my application without setting any socket timeout would solve my problem of accepting the client at any point of time. I am doing this in a separate thread, so this wouldn't block another part of my application.

My concern is since accept() blocks till it gets a call from a client wouldn't this consume any resources, may be like if I don't get a call from the client side program for about a week.

Is there any other way of accepting the client side connection. I don't have any information on when client calls for a socket connection, except that it calls at some point.

1 Answer 1

1

There is no problem with calling accept on a different thread. The thread will be blocked in the call to accept and will not be scheduled by the operating system until a connection in inbound. Practically, if you don't get a connection the entire week your thread will not run on the CPU during this time.

Therefore, it will not consume any CPU resources and only a bit of memory.

Sign up to request clarification or add additional context in comments.

3 Comments

or so we hope ;) It depends on the JVM implementation and perhaps OS (for scheduling). I agree with your post Tudor.
But how will the JVM know there is a connection inbound, may be internally some other thread within the JVM should be constantly hitting the socket to see if there are any inbound connections which might consume resources
'But how will the JVM know there is a connection inbound' - because accept() returns. 'may be internally some other thread within the JVM should be constantly hitting the socket to see if there are any inbound connections' - not on any OS I have ever used. The thread that called accept() is made ready by a signal from a kernel thread running the TCP stack. The kernel threads are, in turn, made ready by signals from the NIC driver and so, originally, from a hardware interrupt. No polling. Like @Tudor says - if nothing tries to connect, nothing will be happening.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.