Sachin
Sachin

Reputation: 18757

How to check if one of the thread has failed?

I have a multi-threaded Java application. I want the whole application to fail is one of the thread encounters any exception.

I don't think doing System.exit(); inside the thread will exit the whole app.

Can someone suggest a way?

Upvotes: 1

Views: 1596

Answers (3)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41220

put try-catch in Thread's run method and in catch block System.exit(0); it works.

Upvotes: 1

jtahlborn
jtahlborn

Reputation: 53694

actually, calling System.exit() will exit the whole app, but that's generally not what you want in your library code (for instance, it makes unit testing difficult).

a better implementation is to have a shared "error handler" reference, with an implementation that you control. in unit tests, you could just log the exception. in your real app, you could call System.exit().

Upvotes: 1

HS Developer
HS Developer

Reputation: 26

One simple way to do that is to have try{} catch{} on each thread, when you catch exception you may call static function that exits the application.

Upvotes: 0

Related Questions