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