0

Hi here are a couple of lines in the code.

UserAccountVO fun() {
  // ...
  ObjectInputStream in = xstream.createObjectInputStream(is);
  return (UserAccountVO)in.readObject();
}

Now its giving the following warning:

leaked_resource: Variable in going out of scope leaks the resource it refers to".

Can anyone please explain it?

This is how I got it fixed:

try(ObjectInputStream in = xstream.createObjectInputStream(is);) {
  return (UserAccountVO)in.readObject();
} catch (IOException e) {
  s_logger.error(e.getMessage());
  return null;
}
Markus Weninger
  • 11,931
  • 7
  • 64
  • 137
user3100148
  • 55
  • 1
  • 7
  • 1
    possible duplicate of [Resource leak: 'in' is never closed](http://stackoverflow.com/questions/12519335/resource-leak-in-is-never-closed) – TheCodingFrog Jul 30 '15 at 08:46

1 Answers1

1

In former case, you are not closing the resource 'in' and that may result in memory leak. Therefore you get a warning. While in later case, you have put the 'in' instantiation within the TRY block which actually adds an implicit 'finally' for you to close the resource.

Hope it clarifies.

Rahul Winner
  • 430
  • 3
  • 16
  • So what you are saying is that I do not need to include finally statement? It gets added automatically. Is it something specific to newer versions of java? Thanks for the replay :) – user3100148 Jul 30 '15 at 09:10