aspose file tools*
The moose likes Threads and Synchronization and the fly likes puzzled with non-static synchronized method accessing static field Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "puzzled with non-static synchronized method accessing static field" Watch "puzzled with non-static synchronized method accessing static field" New topic
Author

puzzled with non-static synchronized method accessing static field

Tapio Niemela
Ranch Hand

Joined: Jan 06, 2006
Posts: 77
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

Joined: Sep 27, 2011
Posts: 14
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

Joined: Aug 22, 2010
Posts: 3610
    
  60

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: puzzled with non-static synchronized method accessing static field