DEV Community

Discussion on: What is an analogy or visualization of a coding concept that really helped you understand it better?

Collapse
 
the_unconventional_coder profile image
ABHINAVA GHOSH (he/him)

A really great analogy i use to differentiate between when and when not to use parallelStreams in Java.

For example if i am searching for my car keys in a room full of 100 people and i know for sure that my car key is under one of the chairs , and 100 people are sitting in the room(1 person/chair):

Lets assume for each person to look under their table it needs 1 second.And suppose i find my key in the 10th chair.

So i have two options:

1) i tell each person one by one to look under the table.

So it will take 10 seconds and 10 people to find my key

Thus time=10seconds

Resources used-10 men

2)i tell all of them to simultaneously look for the car key

so it will take 1 second to search the key

but 100 men

Thus, time=1second
Resource-100 men

Thus this is the very same case with streams vs parallelStreams.

We should always remember that parallelStreams may give better results but also comsumes huge resources.

Hope this analogy will help others!