Hello,

While you discuss TWR hazards, be aware that closing a sink (OutputStream) as part of a "finally" branch which hides exceptions is dangerous in some I/O scenarios because hardware write errors could be delayed until the close. NFS for example has this tendency, but also some virtual filesystems do a lot of commit work on close. So typically you add a close inside the try as well.

Greetings
Bernd


Am 10.10.2013, 04:36 Uhr, schrieb Joseph Darcy <joe.da...@oracle.com>:
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


--
http://bernd.eckenfels.net

Reply via email to