Reputation: 61
I'm using a thread to run a half of an application, and the other half is running by itself. I did this so that the one part fetching the data (because I'm running an infinite loop) would not stop the other part from doing it's job. Now I was wondering: if an exception occurred on one part it would block the some of the other part because they are dependent on each other.
So my question is, how could I prevent an exception from stopping my whole program and make it continue do things?
Upvotes: 1
Views: 1700
Reputation: 127
You can create a boolean variable maybe called running
so that while your while loop is working fine, this variable will be true. Immediately an exception is caught, the variable becomes false. Your main task can then check the variable anytime it wants to use the shared data. If the variable is true, read the data; else, do something else like restarting the thread depending on the type of exception caught.
Remember, in order to make the variable false, you will need to include its update in your catch clause.
There are better and more complex methods out there like the use of ExecutorService
.
Upvotes: 1
Reputation: 2540
Throwing an exception from one thread generally will not impact the runtime of the others. Threads are kind of off in their own little world in that regard.
That said, if two threads are sharing some state (whether directly through the heap or indirectly through a database or something like that) and one thread leaves the application's data in an unstable/corrupted state because it bombed out, that could obviously impact the behavior of the other threads, making them do further "bad stuff." You will want to prevent this whenever possible; best way to do it is to document your exceptions as best you can and to catch and handle them when thrown, and to back your logic with robust unit tests.
Upvotes: 1
Reputation: 21
Try-catch or throw an exception. If neither of those sound familiar, I would look them up.
an example of try-catch
try
{
//your code that may throw exception
}catch(TheException e){
e.printStackTrace(); // or however you handle exceptions
}
good resource for throwing exceptions: https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Upvotes: 1