What is critical section in java multithreading?

Answer: A critical section in java multithreading is a piece of code that access shared resources. Resources can be static variable, any Abstract data types or Data structures e.g. List, queue, stack and vector etc.  And File IO etc.

For example, in below class function func has a critical section block i.e. int j = i + 1;

public class Test {

	static int i = 10; // static variable

	public void func() {

		//synchronized block
		synchronized (this) {
			int j = i + 1;// this statement is a critical section 
			System.out.println(j);
		} 
	}
}

Multiple threads can have object of this class and call function func and can update the static variable i, resulting undesired result. Hence, it has been synchronized. So, only one thread can enter into critical section and update it at a time.

Similarly, there can be many critical sections that can access data structures, List, queue and files etc.

NOTES:

  • Synchronization mechanism is used on critical section in multithreaded application.
  • For synchronization, we can use synchronized block, synchronized methods and semaphore etc. in Java.

Related Posts