The synchronized keyword may be applied to a method or statement block and provides protection for critical sections that should only be executed by one thread at a time.
public class MyClass { public synchronized static String mySyncStaticMethod() { } public synchronized String mySyncMethod() { } {
public class MyOtherClass
{
Object someObj;
public String myMethod()
{
<statements>
synchronized (someObj)
{
<statements affecting someObj>
}
}
}
The synchronized keyword prevents a critical section of code from being executed by more than one thread at a time.
When applied to a static method, as with MySyncStaticMethod in the examples above, the entire class is locked while the method is being executed by one thread at a time.
When applied to an instance method, as with MySyncMethod in the examples above, the instance is locked while being accessed by one thread at at time.
When applied to an object or array, the object or array is locked while the associated code block is executed by one thread at at time.
None.