Synchronizing across multiple classes.

0 moka toka · July 15, 2014
Ok so I want to know how to use synchronized blocks but across classes. What I mean is, I want to have synchronized blocks in more than one class but they're all synchronizing on the same object. The only way that I've thought of how to do this is like this:


//class 1
public static Object obj = new Object();

someMethod(){
synchronized(obj){
//code
}
}


//class 2
someMethod(){
synchronized(firstClass.obj){
//code
}
}


In this example I created an arbitrary Object to synchronize on in the first class, and in the second class also synchronized on it by statically referring to it. However, this seems like bad coding to me. So I wanna know if there is a way you can synchronize on the same object across multiple classes.

Post a Reply

Replies

Oldest  Newest  Rating
0 Pere Garau Burguera · July 15, 2014
Why has it to be in different classes? Can't it be in just one single class? 
0 moka toka · July 15, 2014
In smaller programs, sure. But when getting into bigger programs and you want to separate it into different classes, you need to do this. Even if you don't, I still wanna know how to do it.
-1 Pere Garau Burguera · July 16, 2014
I've always done into the same class, but you can also do it in two different classes if the object you use to synchronize is the same in both classes. So, I think your example would work. Try it and let me know if you have any error. 
0 moka toka · July 16, 2014
Whether I call a getMethod or refer to it directly doesn't really make a difference.. And okay I'll try my code.
  • 1

Java / Android Development

106,931 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator