all synchronized methods in Java critical regions?
Not only synchronized
methods/blocks, code using LockAPI too safeguard critical region ( section)
Multiple ways of guarding critical section.
1. synchronized methods:
public synchronized void incrementCounter(){
++counter;
}
2. synchronized statements
public int getCounter(){
synchronized(this){
return counter;
}
}
3. Lock API
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // block until condition holds
try {
// ... method body, which is critical section
} finally {
lock.unlock()
}
}
}
Useful SE questions:
Why use a ReentrantLock if one can use synchronized(this)?
Avoid synchronized(this) in Java?
are critical regions only found in concurrent systems in Java?
No. They can be found in other languages too.
Related SE question:
C# version of java's synchronized keyword?
Does PHP have the equivilant to Java 'synchronized' , or is this not required?