• Post Reply Bookmark Topic Watch Topic
  • New Topic

Communicating Exception Occured in One Thread and Stopping processing of others  RSS feed

 
Sangel Kapoor
Ranch Hand
Posts: 162
1
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everyone

Please see the below code




In the above code , i am getting java.lang.IndexOutOfBoundException for the reasons i know., but the other thread (which is putting items in the bag) kept running.
I want to stop the processing of that thread when Exception occurs in another thread.

Probably you could answer this by saying to keep a flag and the both threads keep checking that. But i want to know 2 things

1. Best Practice
2. How to communicate Exceptions from one thread to another in General.

Thanks and Warm Regards
 
Devaka Cooray
Marshal
Posts: 5325
575
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The best practice is making the code in a way that exceptions is not a dependency of the flow control of your program. The whole thought of propagating an exception to another thread shows a red flag that you are depending on exceptions for major flow control business. If 'bag' tends to be empty in regular cases, you should better rely on an if-condition to do whatever you want to do when it gets empty. If stopping the thread is all what you want to do, you can just let the thread exit the loop which leads to its termination. If you want to stop the other thread too, a shared flag would work.
 
Sangel Kapoor
Ranch Hand
Posts: 162
1
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just read about the Future and Callable. Can not we use the Future object for the same.

Future#get throws the ExecutionException which wraps the exception we throw from the flag.


Reason why we want to stop all other threads is the condition when partial results from all the other threads is a waste if any of the thread throws an exception.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!