I'm working on a task where I need to make multiple request to an HTTPS url from my java program and read the response. This process is to be repeated multiple times with different requests.
The latency(time difference between request and response) for each request is around 300ms if I use just 1 thread - making requests sequentially.And the throughput is around 3.3 requests per second.
However, as the goal is to get a high throughput number I have decided to go with multiple threads each making a request at given point of time.
Some important details:
I am using only those number of URL instances as number of threads. The idea is that each thread uses a single URL instance and calls new URL(url).openConnection() every time it makes a request.
I'm closing input stream using inputStream.close() each time after reading the response and this closing will make the socket reusable.
I'm not calling httpConnectionURL.disconnect() as this will close the underlying socket.
I have set http.maxConnections to number of threads using System.setProperty("http.maxConnections", threadCount);
I am also checking the number of connections open at any given point of time using "netstat -a | grep | wc -l" and this is always giving a number equat to or above threadcount as expected.
Even after doing all these, I am not getting an expected throughput. For 1 thread when I am getting a throughput of 3.3 I assume using 100 threads I should get a throughput of at least 300 per second.
Can anyone kindly explain me where am I going wrong. or any other better solutions. Below is my code snippet.
Main Class:
public static void main(String[] args)
{
URL[] urlConnArray = new URL[threadCount];
for(int j = 0;j < urlConnArray.length;j++)
urlConnArray[j] = new URL(regURL);
System.setProperty("http.keepalive", "true");
System.setProperty("http.maxConnections", String.valueOf(threadCount));
for(int i=0;i<1000000;i++)
{
Thread regThread = new Thread(new RegisterThread(urlConnArray[i]));
regThread.start();
}
}
RegisterThread Class:
public class RegisterThread implements Runnable
{
httpConn = (HttpURLConnection) urlConnArray[i].openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "application/json" );
//Prepare the request body.....
long requestTime = System.currentTimeMillis();
InputStream is = httpConn.getInputStream();
long responseTime = System.currentTimeMillis();
long latency = responseTime - requestTime;
reader = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null)
{
response.append(line);
}
is.close();
}