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
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Reply 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: 76
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
Bartender

Joined: Aug 22, 2010
Posts: 2385
    
    3

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://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: puzzled with non-static synchronized method accessing static field
 
Similar Threads
Synchronizing thread woes!
How to receive message after sending from client side ?
Threads, that processed two shared ArrayLists like Queue
ActiveMQ 5.2.0 + REST + HTTP POST = java.lang.OutOfMemoryError
Multithreaded Example... Where to put WAIT() , NOTIFY() advise please