简体   繁体   中英

Resource Leak (Resource out of scope)

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM