Friday, May 27, 2016

Java : Context Switching in Multithreading

When there are multiple threads running in the application, then the CPU cycles are pre-empted from one process and provided to another one based on the high priority or any other algorithm that is being used in that.
The pre-empting of CPU cycles from one process so that the CPU can be available to the second process is called as Context Switching.

Context Switching can be explained in a better way by an example of copy and paste that we use daily.

Let us copy a paragraph "Copied Paragraph" by using CTRL+C or copy command and delete this "Copied Paragraph" before pasting the copied content. The paragraph will be pasted wherever you want. That happens because when we copy the paragraph it is copied instantly and pasted in memory context on a common place which is accessible easily to each process. And when we use to paste it anywhere then the content is not coming from the copied address but is coming from that common place where CPU has pasted the content on the time of copy. Hence, a context is used in between the copy and paste processes. It seems that the pasted data is coming from directly the place from where we have copied that but in real the data is getting pasted in the context at the time of copy and is copied again from there and pasted to the location where we want it at the time of paste process. This is called the context switching.

Hence , in Multi-threading when the cycles of a thread are pre-empted then the state of the thread is saved to the context and is resumed from the context when the CPU comes back to this thread to execute its remaining part. So, its impossible to work with threads without context switching. Although its a basic discussion about this topic and one can dig into it much more. 

No comments:

Post a Comment