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

I am sure that this question was asked earlier, but after searching on Google and here I did not find anything.

Here is my situation, I have several threads that write to a file, and the main thread that creates the printing machine and processes the creation of the file and closing the printing device inside the finally block in a try / catch loop. When I run the application inside eclipse, I click the stop / terminate button and there is nothing written in the file. I want to make sure that I am doing everything right here, or if there is a better way to deal with closing the printing device whenever execution stops. Heck, if there is a better way to handle multiple threads writing to a file, I can join this tip (I'm pretty terrible at multithreaded programming right now).

+6
source share
2 answers

There is only a rare fact that, in the end, is not fulfilled. One of them may be: System.exit(0). Using finally assumes that the statement in finally blocks is always executed.

Because of your problem, make sure that your thread has not yet completed your final block: make sure you use synchronization, if necessary - always check it with the test module.

+2
source

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

+2
source

Source: https://habr.com/ru/post/979662/


All Articles