• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

puzzled with non-static synchronized method accessing static field

 
Tapio Niemela
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, I'm really puzzled with example of Dr. Rajkumar Buyya at buyya.com/java/Chapter14.pdf

This is the code on page 384


Shouldn't the generateMessage method be also static, as it is accessing static-field? If not, could someone clever tell my why not ?
Thanks in advance
 
Vladimir Ozerov
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, it should not. Beacause non-static methods can access static fields or methods, but not vice versa: static methods cannot access non-static fields or methods.
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vladimir Ozerov wrote:No, it should not. Beacause non-static methods can access static fields or methods, but not vice versa: static methods cannot access non-static fields or methods.

Generally that is true.

However, the problem here is the synchronization. The non-static, synchronized methods of different instances of this class can be executed in parallel. In this case, the static fields are not accessed from within these methods in a thread-safe way, despite the methods being declared synchronized.

So I'd say the answer to Tapio's question is that the generateMessage() should probably be declared static synchronized, if its purpose is to generate unique messages. The implementation as it was posted is flawed in this regard. However, I'd prefer to use AtomicInteger for that purpose.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic