0

Is there a semantic difference between the following two options? Is any one of them more secure than the other in terms of automatic resource management?

Option1:

 try ( ObjectInputStream in = new ObjectInputStream(new
          FileInputStream("fooFile")) ) {
     ...
    }

Option2:

 try (FileInputStream fin = new FileInputStream("fooFile");
             ObjectInputStream in = new ObjectInputStream(fin)) {
            ...
   }
Geek
  • 26,489
  • 43
  • 149
  • 227
  • I'm not sure, but I think in the second example, both streams are closed separately which might be problematic if the `ObjectInputStream` caches some data and the `FileInputStream` is closed first. – isnot2bad Jul 22 '14 at 13:19
  • @isnot2bad They are always guaranteed to be closed in the reverse order. So in my code above `in` will be closed first and then only `fin` will be closed. So that makes your point moot. – Geek Jul 22 '14 at 13:22
  • The only difference is that you'll get a redundant `close` call on the `fin`, but according to the `AutoCloseable` contract, that won't cause any error. – William F. Jameson Jul 22 '14 at 13:23
  • @WilliamF.Jameson I think you are talking about the second option. if that is true can you please explain the cause of the redundant call? – Geek Jul 22 '14 at 13:25
  • 1
    It's simple, `fin` is declared as a managed resource so naturally it will get its `close` method invoked. It will be redundant because it is at that point already closed (`in.close()` has internally cascaded to `fin.close()`). – William F. Jameson Jul 22 '14 at 13:28
  • 2
    http://stackoverflow.com/a/21348893/1419315 The argument there is, esentially, that with the first variant, `FileInputStream.close ()` will not get called when *construction* of the `ObjectInputStream` fails. – JohnB Jul 22 '14 at 13:29
  • @Geek you're right, closing is done in reverse order. Nevertheless I'd not use the second option unless you really need both stream objects within the try block. – isnot2bad Jul 22 '14 at 13:29
  • @JohnB A very good point, although in this particular case that would be almost impossible. – William F. Jameson Jul 22 '14 at 13:51
  • @JohnB This makes complete sense. You may want to pen the same as an answer and I would accept it. – Geek Jul 22 '14 at 13:57

1 Answers1

1

See here: http://www.stackoverflow.com/a/21348893/1419315

The argument there is, essentially, that with the first variant, FileInputStream.close () will not get called when construction of the ObjectInputStream fails.

JohnB
  • 13,315
  • 4
  • 38
  • 65