aspose file tools*
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
Author

Static method in multi-threaded environment

Alex Del
Greenhorn

Joined: Apr 06, 2013
Posts: 1
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

Joined: Jul 21, 2011
Posts: 177
    
    6

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 8.4.3.6 of JSL. Synchronizing a static function puts a lock on the class object.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static method in multi-threaded environment