Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static method in multi-threaded environment

 
Alex Del
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a "helper" class like this:



How the static methods are handled in a multi-threaded environment? Does the JVM maintain locks and only one thread is allowed at a given time?

Any help in understanding this issue is greately appreciated.
 
Tina Smith
Ranch Hand
Posts: 208
9
Eclipse IDE Firefox Browser Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JVM doesn't maintain locks unless you ask it to. So yes, it is possible that doSomething could be executed by two threads at once.

You can lock doSomething down to one thread at once by adding a synchronized block within the method, or synchronized keyword to the method signature. However, this will lock the Helper.class object, not any particular instance of Helper. If you have:
doSomething and doSomethingElse could be executed concurrently by two different threads. This is because they lock on two different objects: one locks on the class, the other locks on the instance of the Helper object.

And welcome to the ranch!
 
John Vorwald
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See section 8.4.3.6 of JSL. Synchronizing a static function puts a lock on the class object.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Vorwald wrote:See section 8.4.3.6 of JSL. Synchronizing a static function puts a lock on the class object.


Synchronizing doesn't "put a lock on an object." That's a misleading way of putting it. Rather, it obtains an object's lock (or monitor).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic