• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regarding synchronization  RSS feed

 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can we synchronized a static method following way?



ex is a satic reference variable. Is it right?
 
Stephan van Hulst
Saloon Keeper
Posts: 7973
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, but you can also synchronize the method directly. Note that your method is missing a return type.
 
Campbell Ritchie
Marshal
Posts: 56534
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are you using as your exclusion "ex"? It is usual for a static method to use the .class object for its surrounding class, rather than an instance of the class.

At least I think it is. Rob will tell you if I am mistaken.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nope, you're right. Most people would write that code as such (note: the missing return type is still not fixed):
If the entire method body is inside this synchronized block this is the same as this:
After all, synchronization on a static method means using the Class literal to synchronize on.
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah I am very well aware of this fact that we should always syncronize the static method on the class instance (.class).

I just wanted to clarify my doubt if same can be achieved using static reference variable or not? Though I am never going to do it.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only if you make this static reference final. Otherwise, some code could reassign ex and you'd synchronize on a different object.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!