Factors deciding the number of bytes read from the InputStream

243 views Asked by At

The processing of writing data in the ByteArrayOutputStream from InputStream obtained by urlConnection.getInputStream() is taking more than 1 minute.

CODE SNIPPET

URL requestUrl= new URL(_sampleurl_);  
HttpURLConnection urlConnection=(HttpURLConnection)requestUrl.openConnection();  
urlConnection.setConnectTimeout(10000);  
urlConnection.setReadTimeout(10000);  
urlConnection.setRequestMethod("GET");  
urlConnection.connect();  
int statusCode=urlConnection.getResponseCode();   //200  
long contentLengthByTen = urlConnection.getHeaderFieldLong("Content-Length", _defaultSize_); //7631029  
InputStream inputStream = urlConnection.getInputStream();  
final byte[] byteArray = new byte[16384];  
int length;  
ByteArrayOutputStream byteArrOutStrm = new ByteArrayOutputStream();  
int k = 0;  
while ((length = inputStream.read(byteArray)) != -1)  
{  
    byteArrOutStrm.write(byteArray, 0, length);  
    k++;  
} 

Some of the observations are:
The while loop alone executing for more than one minute and it is iterated for around 2650 times.
The HttpURLConnection response code is 200, so the entire content is available in the InputStream.
The Content-Length of the file is 7631029 (bytes).

I have two questions:

  1. Though the byte array size is 16384 and the status code is 200, the inputStream.read method reads only 2800 bytes averagely. Why and which factors decide these bytes?
  2. Proper solution to reduce the processing time?
1

There are 1 answers

1
user207421 On BEST ANSWER
  1. Though the byte array size is 16384 and the status code is 200, the inputStream.read method reads only 2800 bytes averagely. Why and which factors decide these bytes?

The number of bytes available in the socket receive buffer, which in turn is a function of the speed of the sender, the frequency of reads at the receiver, the network bandwidth, and the path MTU. What you're seen isn't surprising: it indicates that you're keeping up with the sender pretty well.

  1. Proper solution to reduce the processing time?

Have the sender send faster. There is nothing wrong with your receiving code, although I wonder why you're collecting the entire response in a ByteArrayOutputStream before doing anything with it. This just wastes memory and adds latency.