课程: Java Practice: Exception Handling

Solution: Multiple Threads - Java教程

课程: Java Practice: Exception Handling

Solution: Multiple Threads

- [Instructor] Here is my solution to the challenge. And you may have had a different one yourself, and that's great. I'm going to start by hiding my test code because we can't change it anyway. And I also want to talk about why I added this challenge. This is because of a problem that I ran into during Java development. When working in a multi-threaded environment, especially when using something like an executor service, sometimes exceptions are not caught. So if I were to have a catch statement to catch all the exceptions here, it wouldn't catch the ones that are thrown even though every single task is throwing an exception. So when you're working in a multi-threaded environment, you need to be pragmatic about handling your exceptions so that you find them when they occur in your code. To do that, you can use something called a future, which holds the result of an asynchronous task. So that would look like this. Future, we'll just call it future, equals that, executor service dot submit. So it takes the result of that and you can look at it later and see whether any exceptions were thrown, et cetera. And we can use that to solve this challenge. So what I'm going to do is hover over future and do the quick fix to import it and that should fix that. So above my exceptions code, I'm going to create a list of futures. We'll call this futures and we'll set it equal to a new array list. And then once we grab the future in the for loop, we'll call futures dot add and then we'll pass in future. After we've done that, and outside of the for loop, I'm just going to loop through all of my futures. So we'll use a for each loop for that. And in here to find the exceptions, I just need to do a try catch block. So try and then we will catch exceptions. We'll call them E. And inside of the try block, I'm going to call future dot get and that's going to return the result of the asynchronous task. If there was an exception, which there will be in every case, then future dot get will throw that exception. When it's caught, I'm going to add it to my exception string list. So exceptions dot add and then E dot get message. With that, I'll hit test my code and confirm that it works. And sure enough, it does. So by using futures, you can capture the values of asynchronous tasks so you can handle exceptions in a multi-threaded environment.

内容