DEV Community

Cover image for Understanding Threading

Posted on

Understanding Threading

Multi-threading is a feature used to process concurrent requests in order to maximize efficiency. Executing one piece of code at a time may work for lightweight programs but can really bog down the system if something heavy needs to be done. One way to think of it is if you are driving a car up a hill that only has one lane. If the road is only passenger cars driving a normal speed then it probably would not be an issue. However if a semi-truck was ahead of you it would take forever to get over the hill. Threading has similar concepts to creating two lanes on the road. With two lanes the cars can drive at different speeds next to each other and the semi-truck isn't slowing the flow of traffic.

Car Driving Up Hill

In reality threads are a bit more complicated. A thread is an execution context, which is information the CPU needs to execute and keep track of a list of instructions. The execution context holds register locations where the next line of instructions is waiting it’s turn. CPU’s give the illusion that they are doing multiple computations at the same time but it is starting and stopping many things very quickly.

Process Chart

Zooming out a bit, you can see in the image above that threads are part of a process. A process is an instance of the program being executed. The threads make up the Process State of the process and contain the information needed to keep track of what still needs to be computed in the program. The process also contains other resources such as the code, data, heap and stack. Some of these resources are shared while others can be thread specific.

Now like everything in programming, if this is such a great boost to efficiency why don’t we apply it to everything? Threads do impose minimal impact, require less overhead to create/maintain/manage, and can provide structure simplification. However, they are much more complicated to implement. They also bring about problems with concurrency. The programmer doesn’t know which order of operations the threads are going to execute so safeguards have to be implemented to guarantee the validity of data. Without protection, one thread may manipulate data that will ruin it for computations by other threads.

Now that we have an understanding of what threading is, next week we will discuss how to implement it in Java! I hope you all have a great week and feel free to leave a comment and a like on the post.






Top comments (0)