I have simple question but has problem to find answer on it.
Question is if synchronized method is equal to synchronized(this) - mean do same locking.
I want to write thread safe code with reduced thread locking (not want use always synchronized methods but sometime partial synchronization critical sections only).
Could you explain me if this code is equal or not and why in short words (examples is simplified to show atomic problem)?
Examples
Is this mixed locking code is equal to brute force code bellow:
public class SynchroMixed {
int counter = 0;
synchronized void writer() {
// some not locked code
int newCounter = counter + 1;
// critical section
synchronized(this) {
counter = newCounter;
}
}
synchronized int reader() {
return counter;
}
}
Brute force code (each method is locked including not critical section:
public class SynchroSame {
int counter = 0;
synchronized void writer() {
int newCounter = counter + 1;
counter = newCounter;
}
synchronized int reader() {
return counter;
}
}
Or I should write this code (this is for sure valid but more micro coding and unclear).
public class SynchroMicro {
int counter = 0;
void writer() {
// some not locked code
int newCounter = counter + 1;
// critical section
synchronized(this) {
counter = newCounter;
}
}
int reader() {
synchronized (this) {
return counter;
}
}
}