Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Jim Janney Newsgroups: comp.lang.java.programmer Subject: Re: unnecessary code in Oracle example? Date: Wed, 09 Oct 2013 14:21:07 -0600 Organization: use only as directed Lines: 73 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx05.eternal-september.org; posting-host="c75a2e3068ccf6c98395286f3e40b97d"; logging-data="5756"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/7SgtT54k22iiolDcGU5el" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.3 (gnu/linux) Cancel-Lock: sha1:n5GTExWtYdaG66di4imH8xl2vCw= sha1:ewX+qqZhW50yjUGrzKqFzHMSGpw= Xref: csiph.com comp.lang.java.programmer:26260 markspace writes: > On 10/9/2013 12:08 PM, Jim Janney wrote: >> >> Thanks. But that looks like a good idiom to avoid. I prefer >> >> MyResource r1 = openResource(); >> try { >> MyResource r2 = openResource2(); >> try { >> // do something >> } finally { >> r2.close(); >> } >> } finally { >> r1.close(); >> } >> >> Not as pretty syntactically, perhaps, but much clearer semantically. >> > > I don't like either one. Why not take advantage of the fact that > resources are specified to be closed in the opposite order that they > are declared in a try-with-resources? > > The following demonstrates this by closing the named streams in the > order C-B-A: > > > package quicktest; > > import java.io.IOException; > import java.io.InputStream; > > public class TryResourcesTest > { > public static void main( String[] args ) throws Exception > { > try( > MyTestStream a = new MyTestStream( "A" ); > MyTestStream b = new MyTestStream( "B" ); > MyTestStream c = new MyTestStream( "C" ) > ) { > System.out.println( a.read()+b.read()+c.read() ); > } > } > } > > class MyTestStream extends InputStream { > > private final String name; > > public MyTestStream( String name ) { > this.name = name; > } > > @Override > public int read() throws IOException { > return 42; > } > > @Override > public void close() { > System.out.println( getClass().getSimpleName()+ > ":"+name+" closed." ); > } > } Yes, in Java 7 you can have clean syntax and clean semantics. Looks like a win all around. -- Jim Janney