Synchronizing threads

In multithreaded applications, there might be situations where multiple threads try to access a shared resource and produce erroneous and unexpected results. We need to ensure that the resource will be used by only one thread at a time, and that can be achieved by synchronization. The synchronized keyword is used to achieve synchronization; when we define any synchronized block in Java, only one thread can access that block and other threads are blocked until the thread inside the block exits that block.

The synchronized keyword can be used with the following different types of blocks:

  • Instance methods
  • Static methods
  • Code blocks inside instance methods
  • Code blocks inside static methods

In Java, a synchronized block degrades performance. We must use the synchronized keyword when required, otherwise, we should use the synchronized block of the critical section only where it is required.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset