What is lock in thread

Showing Answers 1 - 6 of 6 Answers

sandychops

  • Feb 24th, 2015
 

Lock is a thread synchronization mechanism similar to synchronized blocks. From Java 5 the package java.util.concurrent.locks contains several lock implementations which we can use to achieve synchronization.

For example: to synchronize a block of code like

Code
  1. public int increment(){

  2.     synchronized(this){

  3.       return ++count;

  4.     }

  5.   }



Here count++ could lead to Read-modify-write concurrency problem where one thread is updating where as another thread is reading and this could lead to lost update or incorrect read.
So to achieve synchronized we can use the synchronize(this) or implement locks as below


Code
  1. private Lock lock = new Lock();

  2.   private int count = 0;

  3.  

  4.   public int increment(){

  5.     lock.lock();

  6.     int newCount = ++count;

  7.     lock.unlock();

  8.     return newCount;

  9.   }




  Was this answer useful?  Yes

Vishal

  • Jan 1st, 2018
 

When we are working with multiple threads, we have to make sure multiple threads are working on synchronized object otherwise different threads might see different values for same variables.
In order to do that we have synchronization which gives a lock to a particular thread and when this thread releases the lock next thread takes the lock and execute itself.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions