What are synchronized methods and synchronized statements?
Synchronized Methods:When a method in Java needs to be synchronized, the keyword synchronized should be added.
Example:Public synchronized void increment()
{
X++;
}
Synchronization does not allow invocation of this Synchronized method for the same object until the first thread is done with the object. Synchronization allows having control over the data in the class.
Synchronized Statement:A synchronized Statement can only be executed once the thread has obtained a lock for the object or the class that has been referred to in the statement. Synchronized statement contains a synchronized block, within which is placed objects and methods that are to be synchronized.
Example:public void run()
{
synchronized(p1)
{ //synchronize statement. P1 here is an object of some class P
p1.display(s1);
}
}
What are synchronized methods and synchronized statements?
Synchronized Methods:Two invocations of synchronized methods cannot interleave on the same object.
When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Synchronized statements:Another way to create synchronized code is with synchronized statements. Synchronized statements must specify the object that provides the intrinsic lock:
public void add(String str)
{
synchronized(this)
{
str1 = str;
cnt++;
}
strList.add(str);
}
What are synchronized methods and synchronized statements?
Synchronized Methods:Two synchronized methods cannot interleave on the same object.
When a thread of a synchronized method is executing on an object, the other threads invoking synchronized methods on that object are suspended until the first thread has finished.
Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors
Synchronized statements provide finer synchronization than the synchronized methods.