• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchoronization at class level

 
Shahab Mufti
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Letters extends Thread {
private String name;
public Letters(String name) {
this.name = name;
}

public void write () {
System.out.print(name);
System.out.print(name);
}
public static void main(String[] args) {
new Letters("X").start();
new Letters("Y").start();
}
public void run() { synchronized(Letters.class) { write(); } }
}

There is no static synchronized method, but the output is coming as XXYY or YYXX. How synchronized at class level is working here???


 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

Please put your code between the code tags to make it easier to read.



puts a lock on the complete class. That means that if one Thread is executing a method in the Letters class, then no other Thread is allowed to execute any of the other method, no matter if it is the same method or any other method in that class.

This is different from marking a method as synchronized, which only prohibits concurrent access to that very method.
 
Shahab Mufti
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Justin,

Isn't it true that a class-level lock would lock only static synchronized methods of the class?

Thanks
 
Paul Clapham
Sheriff
Posts: 21892
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shahab Mufti wrote:Isn't it true that a class-level lock would lock only static synchronized methods of the class?


There is no such thing as a "class-level lock". There is only synchronization on an object. In your case you happen to have chosen to synchronize on a Class object, but there's nothing special about that choice. When you do that, code running in one block synchronized on the Class object will lock out any other code which is synchronized on that Class object.

Yes, that does include all static synchronized methods but it could lock other code which looks the same as the example given.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Who is Justin?

True, for instances use synchronized(this).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!