0

So, I have a main thread that spawns a bunch of "worker-threads" that works alongside it for the duration of the process. What I want is that if a worker-thread dies from an exception or whatnot, the main thread should also throw a runtime-exception and die peacefully.

This can be achieved by catching the exception in the worker-tread and setting an error-flag before exiting. The main thread then polls this flag and throws an exception if it's set. This can be done by try-catch or setting an exception handler.

My question is whether there's a simpler way that doesn't include polling in the main thread. Something that goes automatic if you know what I mean.

Edit: Well, many claim that setting a handler is the answer and that this is a duplicate. Well, unless I'm mistaking things here, the handler is executed by the thread that throws the exception in the first place, so I still have to set a flag to kill the main thread. I thought this was clear. SO let me clarify;

What I want is that if a worker-thread dies from an exception or whatnot, the main thread should also throw a runtime-exception and die peacefully, without using flags, but have it done "automatically"

Jake
  • 843
  • 1
  • 7
  • 18
  • 2
    Duplicate: http://stackoverflow.com/questions/8362345/defining-one-global-uncaughtexceptionhandler-for-all-threads-of-my-application – Shloim Dec 01 '15 at 08:19
  • Nope, it's not the same question – Jake Dec 01 '15 at 08:25
  • Well it's not _exactly_ the same question, but very similar and the thread contains everything you need. – mad_manny Dec 01 '15 at 08:30
  • Not exactly, but UncaughtExceptionHandle is your go-to implementation here. – Shloim Dec 01 '15 at 08:30
  • Ok, the problem as I see it is that given my own experience the uncaughtExceptionHandler works no different than a try-catch block and I have to set a flag in either case, since the handler is executed by a worker-thread and not by the main thread, just as I've written. That still means I have to poll some state in the main thread. At least that's what I had to do when I tried it the last time. – Jake Dec 01 '15 at 08:41
  • What is the main thread going to _do_ when it sees the flag set? Why can't the exception handler for the dying thread just do the same thing instead of asking the main thread to do it? – Solomon Slow Dec 01 '15 at 13:06
  • I want the main thread to throw a runtime exception. That's my question. Can one thread make another thread to throw an exception directly, without flags – Jake Dec 01 '15 at 13:14

1 Answers1

0

Have a CountdownLatch in the main thread, have it wait on the CountdownLatch.

When a thread exits decrement the CountdownLatch. When that happens have the main thread act appropriately.

Tim B
  • 40,716
  • 16
  • 83
  • 128