3

I want to understand the following, suppose I have following block of code:

try{
    // do something
    asynchronousMethodCallThatWritesFileOutputStreamToSocket(fileOutputStream);
}catch (SomeException e){
    //handle exception
}finally{
    closeFileOutputStream(fileOutputStream);
}

My question is will the finally block close stream before asynchronous method finishes? Or will it somehow await? Please, any quotes from the books, if you know. Thank you very much.

N.B. This is pseudo-code, I know try-with-resources patterns.

Evgeniy Mishustin
  • 3,343
  • 3
  • 42
  • 81
  • 1
    It will at least try to close. The point in using an asynchronous call is not wanting to wait for it to finish. So you should close the resource either inside the asynchronous call or in a "finished" - callback. BTW: You could have easily found that out ... – Fildor Jul 11 '16 at 11:48
  • exactly. I've just found such block in code, and I'm trying to predict what will happen – Evgeniy Mishustin Jul 11 '16 at 11:49
  • 1
    Well, I'd expect an Exception to be thrown either in the writing thread or in the thread that is trying to close the file. Look out for try/catches that silently swallow Exceptions ... But prediction is hard, because it is still possible (though not probable) that the asynchronous call is executed fast enough so that the close will be done after it is through. – Fildor Jul 11 '16 at 11:50
  • 2
    Logically your async method should close the Streams. It shouldn't be closed where async call is made – PEHLAJ Jul 11 '16 at 11:52
  • 1
    Why don't you simply test it instead of trying to *predict*? – Manu Jul 11 '16 at 11:54
  • 1
    If I had designed this, I'd just give the path and have file stream open/closed inside the asynchronous call. – Fildor Jul 11 '16 at 11:54
  • @Fildor, great idea, thanks – Evgeniy Mishustin Jul 11 '16 at 12:01

1 Answers1

4

The program is exited always with an uncaught exception because the async function is not try-catched correctly.

Basing on Java Asynchronous Exceptions: Can I catch them?

The only problem is that they (exceptions, ndr) may occur at any place in your program, so catching them reliably is hard. You would basically have to wrap the run method of all threads and the main method in a try..catch block, but you can't do that for threads you don't control (like the Swing EDT, or threads for timers etc.).

Community
  • 1
  • 1
morels
  • 2,095
  • 17
  • 24