Search code examples
javadatainputstream

Is dumping a lot of DataInputStreams bad practice?


Let's say I have a data class that holds a 3-dimensional vector.

class Vec3 {
    float x, y, z;
    public Vec3(float x, float y, float z) { /* ... */ } 
} 

Then I want to give it the functionality to be read from a stream. I have floats, so the easiest choice is a DataInputStream.

public static Vec3 read(DataInputStream in) {
    float x = in.readFloat();
    float y = in.readFloat();
    float z = in.readFloat();
    return new Vec3(x, y, z);
} 

And, of course, I want it to support all InputStream types. So, I'll create an overload that wraps any stream.

public static Vec3 read(InputStream in) {
    return read(new DataInputStream(in));
} 

However, this method creates a DataInputStream that is never closed and just dumped after reading. Is this bad practice and can it cause problems? What if I have a lot of Vec3's to read?


Solution

  • A DataInputStream is a thin wrapper over InputStream, with almost no resources of its own. Their close() method only closes the wrapped input stream. Creating lots of them only means creating many temporary objects for the GC to collect. There is no danger in creating and discarding many DataInputStream objects, but if you are trying to optimize for performance you may want to avoid it.

    On the other hand, trying to support all input stream types seems like an over-generalization to me. I would make the method accept just DataInputStream, or the DataInput interface.