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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With