On 10/9/2013 6:18 PM, David Holmes wrote:
cc'ing Joe Darcy. :)
Joe: there is a try-with-resources question for you below ...
On 9/10/2013 11:20 PM, Sean Mullan wrote:
On 10/09/2013 05:14 AM, Erik Joelsson wrote:
On 2013-10-09 06:33, David Holmes wrote:
In the tool this code doesn't show correct use of try-with-resources:
51 try (BufferedReader br = new BufferedReader(new
FileReader(args[0]));
52 BufferedWriter bw = new BufferedWriter(new
FileWriter(args[1]))) {
The FileReader and FileWriter should also be covered by TWR:
try (FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(args[1]);
BufferedWriter bw = new BufferedWriter(fw)) {
I'm not familiar with the try-with-resources, but calling close on a
BufferedReader/writer will close the underlying reader/writer so
nothing
will be left open, will it not?
That's what I thought as well. David?
It maybe that I am overly pedantic with this but the issue is that
with the original code if the BufferedReader/Writer constructors throw
an exception then the FileReader/Writer that was already created would
not be closed. The revised code accounts for this.
Joe: what is best-practice here? I see a lot of examples of t-w-r
where there is a set of chained I/O streams and only the outermost one
is a t-w-r resource. And that seems wrong to me.
It is a hazard (I thought I had published a blog entry on this very
tropic, but apparently not). The most robust pattern is
try(OriginalResource r1 = new OriginalResource;
WrappingResource r2 = new WrappingResource(r1);
AnnotherWrappingResource r3 = new WrappingResource(r2)) { ...}
One thing to watch out for in this pattern is a non-idempotent close.
Calling close on r3 will presumably propagate a close call to r2, and
then r2 to r1. So give the desguaring the try-with-resource and the
expected behavior of the wrapping in a normal termination situation,
close on r3 gets called once, close on r2 gets called twice (first from
the close on r3, second close from try-with-resources), and close on r1
gets called three times.
HTH,
-Joe