What is critical section in java multithreading?

(Last Updated On: March 9, 2017)

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;

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.