Context Switching in Java Thread Example - onlyxcodes

Saturday 13 May 2023

Context Switching in Java Thread Example

In this tutorial, I will show you context switching using a Java thread example.


A thread is a unique flow of execution within a program in Java. Context switching is the process of preserving one thread's state to allow for the execution of another thread.


This is crucial because it makes it appear as though the program is running in numerous threads at once, even though the CPU can only handle one thread at a time.


context switching in java thread example

Here I provided the illustration of Java context switching:


public class ContextSwitchingExample implements Runnable 
{
    
    private int count;
    
    public void run() 
	{
        for (int i = 1; i <= 5; i++) 
		{
            System.out.println("Thread " + Thread.currentThread().getId() + " Count: " + count++);
        }
    }
    
    public static void main(String[] args) 
	{
        Thread thread1 = new Thread(new ContextSwitchingExample());
        Thread thread2 = new Thread(new ContextSwitchingExample());
        
        thread1.start();
        thread2.start();
    }
}

ContextSwitchingExample, a class in the example above, implements the Runnable interface. 


The thread's code is executed in the run() method. In this instance, it simply publishes a message containing the thread ID and the count variable's current value.


I have created two threads, thread1 and thread2, and launch them both in the main() method. 


When thread1 begins running, it will do so for a brief period of time before being stopped so that thread2 can run. This is the process of context switching in action. 


In order for thread2 to resume execution, the CPU remembers the state of thread1, together with the value of count. 


After thread2 has finished running for a little period of time, it will once more be paused so that thread1 can carry on. The cycle will keep on until both threads have finished running.


What is Context Switching in Multi-Threading Java with Example

Context switching in multi-threading programming refers to the procedure of shifting the CPU's focus from one thread to another. 


This is done to maximize the use of CPU resources while enabling the parallel operation of several threads.


The CPU shifts to another thread to carry out its instructions when a context switch takes place, saving the state of the active thread in the process. Because only one thread may run at a time on a single-core CPU, this enables the CPU to appear to execute instructions from many threads simultaneously.


Here's an example.


public class ContextSwitchingExample implements Runnable 
{

   public void run() 
   {
      for(int i=1; i<=5; i++) 
	  {
         System.out.println("Thread " + Thread.currentThread().getId() + " is running: " + i);
      }
   }

   public static void main(String[] args) throws InterruptedException 
   {
	   
      Thread thread1 = new Thread(new ContextSwitchingExample());
      Thread thread2 = new Thread(new ContextSwitchingExample());
      
      thread1.start();
      thread2.start();
      
      thread1.join();
      thread2.join();
	  
   }
}

ContextSwitchingExample, a class that implements the Runnable interface, is created in the example above. The thread ID and a counter variable are all that the run method does to print out a message.


Two threads are created and launched in the main method. The join function is then used to wait for both threads to finish.


When we execute this program, context switching may cause the output to be interleaved in what appears to be a random order:


Output:


The two threads are operating simultaneously in this output, however, due to context switching, their execution is interspersed. This enables both threads to advance and effectively use CPU resources.


Thread 10 is running: 1
Thread 11 is running: 1
Thread 10 is running: 2
Thread 11 is running: 2
Thread 11 is running: 3
Thread 11 is running: 4
Thread 11 is running: 5
Thread 10 is running: 3
Thread 10 is running: 4
Thread 10 is running: 5

Frequently Asked Questions

What is Context Switching Explain?


Context switching is a method that allows a computer's CPU (Central Processing Unit) to manage many activities or processes by preserving and restoring its state.


When a computer multitasks, it must transition between tasks or processes in order to appear to be executing several programs simultaneously. 


In order to accomplish this, the CPU stores the state of the currently running program or process, along with its register values, program counter, and other relevant data, and then loads the state of the upcoming program or process to be executed.


Context switching can affect a system's performance since it uses resources to save and restore the state of the CPU. Modern operating systems must, nevertheless, deliver a smooth user experience and effective resource management.


Modern operating systems must, nevertheless, deliver a smooth user experience and effective resource management.


In Thread, Context Switching is High or Low


Depending on the workload and available resources in a computer system, thread context switching might occur more or less frequently. 


Thread context switching entails saving one thread's current state and restoring another thread's preserved state. The performance of the system may be impacted by this operation's resource requirements.


A system may experience frequent thread context switching if it has a high number of threads and few resources. 


On the other hand, the frequency of thread context switching may be low if the system has enough resources and few threads. 


The overhead of thread context switching may also be reduced by improvements in some operating systems and processors, which would have a less significant overall effect on performance.


Why Context Switching is Faster in Threads


Because threads share the same memory area as a process, whereas processes have independent memory spaces, context switching is typically faster in threads than in processes. 


This implies that instead of reloading an entirely new memory space whenever a context transfer between threads occurs, the operating system basically needs to update the required CPU registers and program counters.


Additionally, threads typically have lesser overhead for creating and removing them than processes because they are lighter in weight. This implies that switching between threads is quicker and simpler than switching between processes.


Overall, context switching between threads is quicker than context switching between processes due to shared memory space and lower overhead.


Context Switching Between Threads vs Processes


In computers, the term "context switching" is used to describe the process of transitioning from one task to another. This can occur in a multitasking environment between threads or processes.


Within a single process, there are little execution units called threads. Switching between threads is quicker and more effective than switching between processes since they share the same memory area and other resources of the process.


Processes, on the other hand, are autonomous entities with their own memory and resources. As the operating system must preserve and restore the state of the entire process, switching between processes involves greater overhead than switching between threads.


As a result, switching between processes is typically slower than switching between threads. However, there are certain benefits to using several processes, such as better task division, increased dependability, and the capacity to utilize many processors or cores in a system.


Overall, the decision to multitask using threads or processes depends on the particular requirements of the program and the system resources available.


Read Also:

What does double mean in Java

How to Remove a Character from a String in Java

How do you define a method in Java?

What do the replaceAll () do in Java?

Can I use LeetCode for Java?

How to Get the Length of a String in Java

How to make lists of lists in Java?

How to print each word in new line in Java

Why do we use :: (double colon) in Java

What is the Difference Between NoClassDefFoundError and ClassNotFoundException in Java

How to Replace a Character in a String in Java without using the Replace Method

What are Variable Arguments in Java

Java Stream Iterate Example

What Are the 4 types of loops in Java

How to Run Package Program in Java using Command Prompt

What is final class and method in Java

What is Encapsulation in Java with Realtime Example

3 Ways to Create Thread in Java

Java Code to Send Email with Attachment

How to Produce and Consume Restful Webservice in Java

No comments:

Post a Comment

Post Bottom Ad