8

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).

CBredlow
  • 2,790
  • 2
  • 28
  • 47
  • During development you can perhaps flush after every write. – aioobe Dec 15 '14 at 21:31
  • Some insights (regarding finally on termination) : http://stackoverflow.com/questions/1410951/how-does-javas-system-exit-work-with-try-catch-finally-blocks – TJ- Dec 15 '14 at 21:32
  • @aioobe Didn't think of that. Just using this for a personal test, not to production, so I'll try that. – CBredlow Dec 15 '14 at 21:35
  • I'd guess no, especially with your description of the problem. Likely Eclipse just uses the (unsafe, deprecated) Thread.stop() to nuke your app, and so no code at all is executed after that. – markspace Dec 15 '14 at 21:35
  • @TJ- Aha! That might be helpful, I guess I couldn't phrase it correctly. However I still would like some better multithreading advice, so should I just edit my question to reflect that? – CBredlow Dec 15 '14 at 21:35
  • You can never be sure your `finally` blocks will always be executed. For all you know, the OS might terminate your JVM at any point and there's nothing the Java runtime can do about that. You can try your best (flush & close ASAP, which may be slow), but you can never be sure. – GPI Dec 15 '14 at 21:39
  • @markspace Actually, eclipse uses a separate process to run the program and uses `Process.destroy()` when the Terminate button is pressed. – RealSkeptic Dec 15 '14 at 21:41

2 Answers2

2

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.

ServerSideCat
  • 1,992
  • 3
  • 18
  • 24
2

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.

Lofty
  • 96
  • 3