0

I'm trying to implement a tcp client based on classic I/O. In order to reduce negotioation latency I decided to create a connection pool to the server which looks like this:

BlockingQueue<Socket> connections = //

Every time a thread trying to communicate with the server it does the following:

Socket s = null;
try{
    Socket s = connections.take();
    if(s.isClosed())
       s = //create a new connection
    //send data to the server
} finally { 
    if(!connections.offer(s))
        throw new IllegalStateException();
}

I'm not sure if it's common to do like this. At least I have not heard about such an approach. Can someone suggest something that's more common.

user207421
  • 305,947
  • 44
  • 307
  • 483
St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • `isClosed()` doesn't do what you think it does, but otherwise this is a standard approach, – user207421 Aug 14 '17 at 10:46
  • @EJP Did not quite understand. Documentation says that it returns if a `Socket` has been closed. What's wrong? – St.Antario Aug 14 '17 at 10:48
  • @EJP Ah... u mean to replace it with `isConnected()`? – St.Antario Aug 14 '17 at 10:49
  • 3
    The only way a `Socket` can be closed is if you closed it, in which case it shouldn't be in the connection pool at all. It doesn't tell you whether the *connection* has been closed. `isConnected()` is no improvement. You should only put the socket back in the pool if there weren't any problems with it, not in a `finally` block. – user207421 Aug 14 '17 at 10:50
  • If you want to know how to tell if the connection has been closed see https://stackoverflow.com/questions/10240694/java-socket-api-how-to-tell-if-a-connection-has-been-closed – Oleg Aug 14 '17 at 10:58

0 Answers0