Reputation: 37
I have two classes B and C that implements the interface A. In both classes exist a method with a statement that needs to be synchronized. I have this:
class B implements A {
@Override
public void method(){
//some code here
synchronized (this.getClass()) {
//some code here
}
}
}
class C implements A {
@Override
public void method(){
//some code here
synchronized (this.getClass()) {
//some code here
}
}
}
I need to synchronize the statements in both classes but with this.getClass return different classes and it can execute at the same time. How can I synchronized these two statement from different classes in a way that it will execute only once at the same time?
Upvotes: 2
Views: 93
Reputation: 3153
You can easily modify your code without introducing a new class/variable to do exactly what you want (assuming you want to synchronize all implementations of A):
synchronized (A.class) {
// do something
}
This is not a good solution however. The right way to do it is using a lock.
Upvotes: 0
Reputation: 8879
Synchronized block in java is synchronized on some objects. synchronized blocks synchronized on same object reference only allows 1 thread at a time. other will be blocked until it leaves. So use same object reference for both methods. https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
Upvotes: -1
Reputation: 7956
You could declare a shared monitor object in A
, for example:
static final Object MONITOR = new Object();
Then use synchronized(MONITOR)
in B
and C
.
Upvotes: 1
Reputation: 26185
The most likely reason for needing to synchronize them is that they are going to access some common object. If so, synchronize on that object.
If not, and if you control interface A, you can add:
public static final Object LOCK = new Object();
and have them both synchronize on A.LOCK.
Upvotes: 2
Reputation: 207006
Synchronize on some other object that both implementations of method()
have access to.
class D {
public static final Object SYNC_OBJ = new Object();
}
class B implements A {
@Override
public void method(){
//some code here
synchronized (D.SYNC_OBJ) {
//some code here
}
}
}
class C implements A {
@Override
public void method(){
//some code here
synchronized (D.SYNC_OBJ) {
//some code here
}
}
}
Upvotes: 1