Reputation: 2713
What is the difference between synchronized and lock in Java?
Upvotes: 2
Views: 549
Reputation: 2840
Both synchronized
keyword and Lock
objects are used to achieve synchronization in Java. Synchronized
operates on monitor mechanisms that each Object
in Java possess while lock is a simpler object which is a building block of the monitor. i believe basically the question is about the difference between a monitor and a lock.
A lock such as a semaphore
, is a simple mechanism that can achieve synchronization by mutual exclusion only. If one thread acquired (lock.acquire()
) a particular lock no other thread can acquire the same lock until the first thread releases it (lock.release()
). A monitor on the other side operates not only on mutual exclusion but on condition variables as well. In a scenario where thread T1
enters the monitor of an object thread T2
intends to enter the same monitor, T2
will wait until T1
exits the monitor and in modern JVM T2
will actually enter the monitor right after T1
exits.
Upvotes: 1
Reputation: 43600
synchronized
is a language keyword; Locks are objects.
When a method or block of code is marked synchronized, you are saying that some lock object (which could be specified in the syntax of synchronized) must be obtained by the method or block before it can be executed.
Upvotes: 2