Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedInputStream to ByteArrayOutputStream very slow

Tags:

java

bytearray

I have a problem very similar to the link below:

PDF to byte array and vice versa

The main difference being I am trying to interpret a Socket connection via a ServerSocket containing Binary, rather than a file. This works as expected.

However, the problem I am having is that this process is taking quite a long time to read into memory, about 1 minute 30 seconds for 500 bytes (although the size of each stream will vary massively)

Here's my code:

BufferedInputStream input = new BufferedInputStream(theSocket.getInputStream());
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();

while ((bytesRead = input.read(buffer)) != -1)
{
    output.write(buffer, 0, bytesRead);
}

byte[] outputBytes = output.toByteArray();

//Continue ... and eventually close inputstream

If I log it's progress within the while loop within the terminal it seems to log all the bytes quite quickly (i.e. reaches the end of the stream), but then seems to pause for a time before breaking out of the while loop and continuing.

Hope that makes sense.

like image 682
D4y Avatar asked Feb 25 '14 12:02

D4y


People also ask

Why is BufferedInputStream fast?

With a BufferedInputStream , the method delegates to an overloaded read() method that reads 8192 amount of bytes and buffers them until they are needed. It still returns only the single byte (but keeps the others in reserve). This way the BufferedInputStream makes less native calls to the OS to read from the file.

Does ByteArrayOutputStream need to be closed?

In summary: It does no harm to flush() or close() a bare ByteArrayOutputStream . It is just unnecessary. It is often necessary to close an output pipeline that ends in a ByteArrayOutputStream , but this is not because of memory usage or GC considerations.

Is InputStream slow?

InputStream runs faster than Reader .

Is FileInputStream buffered?

BufferedInputStream is buffered, but FileInputStream is not.


1 Answers

Well you're reading until the socket is closed, basically - that's when read will return -1.

So my guess is that the other end of the connection is holding it open for 90 seconds before closing it. Fix that, and you'll fix your problem.

like image 189
Jon Skeet Avatar answered Sep 30 '22 13:09

Jon Skeet