Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does finally() get called when the stop button is pressed in eclipse?

I'm sure this question has been asked before on here, but after searching around google and here I couldn't find anything.

Here's my situation, I've got multiple threads writing to a file, and a main thread that creates a print writer and handles creating the file and closing the print writer inside a finally block in a try/catch loop. When I run the application inside eclipse, I would press the stop/terminate button, and the file doesn't have anything written to it. I want to ensure that I'm doing everything correct here, or if there's a better way to handle closing a print writer whenever execution is terminated. Heck, if there's a better way to handle multiple threads writing to a file, I'm welcome to that advice (I'm pretty terrible at multithreaded programming right now).

like image 241
CBredlow Avatar asked Dec 15 '14 21:12

CBredlow


2 Answers

There is only rare fact that finally isn't executed. One of if can be: System.exit(0). Using finally assumes that the statement in finally blocks is always executed.

Due to your problem make sure that your thread haven't executed already your finally block: make sure you use synchronization if it is needed - check it always with the unit-test.

like image 113
ServerSideCat Avatar answered Sep 23 '22 03:09

ServerSideCat


You need to join your main thread to the other threads before calling the flush() and close() methods in the finally block, so that your main thread will wait for the other threads to finish writing to the file before closing it.

like image 41
Lofty Avatar answered Sep 23 '22 03:09

Lofty