Re: Alternative to System.runFinalizersOnExit()?
Thomas Hawtin <usenet@tackline.plus.com> wrote or quoted in
Message-ID: <455a02fc$0$8733$ed2619ec@ptn-nntp-reader02.plus.net>:
// STILL WRONG (and daft):
OutputStream out = null
try {
out = new BufferedOutputStream(
new FileOutputStream(file)
);
...
out.flush();
} finally {
if (out == null) {
out.close();
}
}
What if construction of the BufferedInputStream failed due to lack of
memory, or some other reason? Leak.
( I assume that the above "if (out == null)" is mis-typed out.)
Why still wrong ?
Though an exception is thrown because of some reason,
'finally' block will be executed.
For the worst.
Even if the lack of memory happens, 'file' resource will be released.
Execute the following code.
Even if OOME is thrown, the lock of "a.txt" is released.
<code>
void test() throws Exception {
OutputStream out = null;
try {
RandomAccessFile lock;
File f;
f = new File("a.txt");
lock = new RandomAccessFile(f,"rw");
if (lock.getChannel().tryLock() != null) {
System.out.println("Lock OK");
}
f = new File("b.txt");
out = new FileOutputStream(f);
out = new TBufOutputStream(out);
out.flush();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (out != null) {
out.close();
}
}
}
class TBufOutputStream extends BufferedOutputStream {
public TBufOutputStream(OutputStream out) {
super(out);
long[] arr = new long[Integer.MAX_VALUE];
}
}
</code>