I have a confusion about object lock.
The below class having 4 methods, the method addB() is synchronized.
In my scienario, there are 4 threads. When a thread-2 access the addB() method (it creates a lock on Test object), will there any other thread access addC() or addD() same time?
Does the Object lock allows only one thread at a time ?
class Test{
private Integer a;
private Integer b;
private Integer c;
private Integer d;
public void addA(){
synchronized(a) {
a++;
}
}
public synchronized void addB(){
b++;
}
public void addC(){
c++;
}
public void addD(){
d++;
}
}
EDIT:
I have 3 threads(t1, t2 and t3) , and each one is going to access addB(), addC() and addD(). If thread t1 access the method addB(), could thread t2 access addC() method simultaneously? If not what would be t2 state?
class Test{
private Integer a;
private Integer b;
private Integer c;
private Integer d;
public void addA(){
synchronized(a) {
a++;
}
}
public synchronized void addB(){
b++;
}
public synchronized void addC(){
c++;
}
public synchronized void addD(){
d++;
}
}
A lock does indeed allow only one thread at a time, but different locks do not affect each other.
In your example, you have two locks – one on the mutex belonging to
a, and one on the mutex belonging tothis(which is implicit when you use thesynchronizedkeyword, as you correctly mentioned in your post).So calls to
addB()will be synchronized but will not block calls to any other method. If one thread holds the lock onthis, another thread can hold the lock ona, and multiple other threads can executeaddC()andaddD()concurrently.Edit: as an aside, you might be interested to learn about the
AtomicIntegerclass if you really are working withIntegers. They provide atomic operations such that you don’t need to worry about synchronizing around them.