Recently, I began to study Java-8 threads. I look at a huge code base and try to figure out where I can use threads to improve performance.
From what I understood, replacing each loop with threads does not make sense, since threads are not always better than loops. Below are a few examples that I have understood as useful:
- If only some elements in the collection lead to more calculations.
while(iterate over a collection)
{
if(certain condition is met) { //do some computation }
else { //do nothing }
}
Using threads here avoids loading unnecessary collection members here. (faster and more efficient in terms of memory)
- when we want to collect the results in a collection where the resulting order does not matter and each iteration is independent (no state). If the computation is CPU intensive and we use parallel threads here, I think it will be more efficient.
Please correct me if I am wrong. I am looking for more such cases ...
source
share