Socket[] clientSocket = new Socket[50]();
DataInputStream[] clientIS...;
DataOutputStream[] clientOS..;
Boolean[] freeConnections = new Boolean[50]();
// initialize all connections
public ConnectionManager (String address, int port)
{
for(int i=0; i<50; i++)
{
clientSocket[i] = new Socket(address, port);
clientIS[i] = new DataInputStream(clientSocket.getInputStream());
clientOS[i] = new DataOutputStream(clientSocket.getOutputStream());
}
}
public String sendMessage(Request request)
{
outputQueue.put(request);
int i = AquireConnection();
clientOS[i].write(request.body);
string body = clientIS[i].read();
inputMap.put(request.Id, body);
return "";
}
// retrieve the index of the first free connection
int AquireConnection()
{
synchronized(this)
{
for(int i=0;i<50; i++)
{
if (freeConnections[i] == true)
{
// mark connection as used
freeConnections[i] = false;
return i;
}
}
}
// no connection available
return -1;
}
ReleaseConnection(int i)
{
synchronized(this)
{
freeConnections[i] = true;
}
}
A simple approach is to create thread safe list(or hash list) of buffers and every time when you receive something you will put also in that list. When that buffer is no longer available on your connection just remove it also from list or hash list.