Resource Leakage

R

Ramesh

Hi Group -

I am having a doubt regarding the resource cleanup. When we open a
resource we need to close the resource after the usage. For example, a
file, database connection and a socket etc...

Take the following scenarios :

<code>
public Properties getPropertiesOne(File file) {
Properties props = new Properties();
InputStream in = null;
try {
in = new FileInputStream(file);
props.load(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// swallow
}
}

return props;
}


public Properties getPropertiesTwo(File file) {
Properties props = new Properties();
try {
props.load(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return props;
}
</code>

The getPropertiesTwo(File file) method is opening the stream but not
closing. Will this cause a resource leakage?

Another scenario when we use XSL transformation we pass streams to
XSLTransformer. In these cases how we can ensure that the file opened
is closed? Is this an anti pattern?
Please advice.

Kind Regards,
Ramesh Mandaleeka
 
S

steve

Hi Group -

I am having a doubt regarding the resource cleanup. When we open a
resource we need to close the resource after the usage. For example, a
file, database connection and a socket etc...

Take the following scenarios :

<code>
public Properties getPropertiesOne(File file) {
Properties props = new Properties();
InputStream in = null;
try {
in = new FileInputStream(file);
props.load(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// swallow
}
}

return props;
}


public Properties getPropertiesTwo(File file) {
Properties props = new Properties();
try {
props.load(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return props;
}
</code>

The getPropertiesTwo(File file) method is opening the stream but not
closing. Will this cause a resource leakage?

Another scenario when we use XSL transformation we pass streams to
XSLTransformer. In these cases how we can ensure that the file opened
is closed? Is this an anti pattern?
Please advice.

Kind Regards,
Ramesh Mandaleeka

yes, it is a leak

steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top