File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Static method in multi-threaded environment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Static method in multi-threaded environment" Watch "Static method in multi-threaded environment" New topic

Static method in multi-threaded environment

Alex Del

Joined: Apr 06, 2013
Posts: 1

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

Joined: Jul 21, 2011
Posts: 208

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!

Everything is theoretically impossible, until it is done. ~Robert A. Heinlein
John Vorwald
Ranch Hand

Joined: Sep 26, 2010
Posts: 139
See section of JSL. Synchronizing a static function puts a lock on the class object.
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

John Vorwald wrote:See section 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).
I agree. Here's the link:
subject: Static method in multi-threaded environment