• Post Reply Bookmark Topic Watch Topic
  • New Topic

static methods and threads

 
Jeremy Hare
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Quick question. Are static methods thread safe? ie. can 2 threads run the same static method simultaneously?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's nothing special about static methods, with regard to thread safety. If they access shared objects, then such access will usually need to be controlled by synchronisation; this might be on the object being accessed, some higher-level object or a special object allocated purely as a lock. The only way that you might think of them as special is that there's no instance of the Class on which you can synchronise.
You can declare a static method as synchronised. If you do, it will be synchronised on the single Class object of the class in which it is declared. This means that only one thread can be executing any part of the method at any one time. However, I understand that the Java Runtime itself sometimes synchronises on this Class object for its own reasons, therefore you might sometimes find a synchronised static method blocks when no other thread is executing it. Usually better, therefore, to explicitly synchronise on some object or other, than to use synchronised static methods.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!