hp1res / io-tools

Automatically exported from code.google.com/p/io-tools
BSD 3-Clause "New" or "Revised" License
0 stars 0 forks source link

Instantiation issue with class members #38

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
There is a rather tricky problem with the current code of the 
InputStreamFromOutputStream.

Unless I'm wrong, the InputStreamFromOutputStream constructor submit the 
DataProducer class thread at class instantiation time, hence ends up calling 
the InputStreamFromOutputStream#produce method although the constructor hasn't 
been fully invoked yet.

Let's imagine the following pseudo-code:

public class MyStream extends InputStreamFromOutputStream {
    private final MyObject obj;
    public MyStream(MyObject obj){
       super(); // starts up the DataProducer thread
       this.obj=obj;
    }

    protected Object produce(OutputStream sink){
        sink.write(this.obj); // this.obj can be null here !!
    }
}

There is no easy way to safely initialize instance variables at this point and 
I get NullPointerException quite frequently in my application.

I would suggest to submit the thread lazily on the first read() invocation.

Cheers,

Nic.

Original issue reported on code.google.com by nlesc...@gmail.com on 30 Jul 2014 at 9:04