Search code examples
javavariablesgarbage-collectioninputstreamlocal

Is it valid to create a ByteArrayInputStream from a local variable?


Suppose a function like:

InputStream func() {            
       byte[] buffer = new byte[] {0,1,2,3};

       return new ByteArrayInputStream(buffer);
}

if I call that function, is there a possibility that the garbage collector deletes the 'buffer' variable and the InputStream doesn't work anymore?


Solution

  • Is there a possibility that the garbage collector deletes the 'buffer' variable and the InputStream doesn't work anymore?

    No, the garbage collector is not allowed to remove objects which are still referenced. The object is referenced from within the ByteArrayInputStream object (its interal buf member references that object).