954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Is there any problem if a static method is accessed by mutiple threads at once

I have a kind of doubt, suppose I have a class like this:

public class AA{

    public static createUser(String a, int b){
        User usr=new User(a,b);
        BB.storeUser(usr);
    }
}


Now, if multiple threads call this createUser() method of this class at the same time, will it cause any kind of problem. Do I need to make it synchronous? It is not going to do any sophisticated task, it will just create a User object and call a function to store it.

warlord902
Junior Poster
120 posts since Dec 2010
Reputation Points: 19
Solved Threads: 0
 

This should be fine, but you probably want the BB storeUser() method to apply a lock to the data structure where it is placing the usr object.

rubberman
Posting Virtuoso
1,565 posts since Mar 2010
Reputation Points: 277
Solved Threads: 179
 
This should be fine, but you probably want the BB storeUser() method to apply a lock to the data structure where it is placing the usr object.

Means unless we are updating or modifying something there is no need to make such methods synchronous?

warlord902
Junior Poster
120 posts since Dec 2010
Reputation Points: 19
Solved Threads: 0
 
Means unless we are updating or modifying something there is no need to make such methods synchronous?

This will be true most of the time, but if you are accessing more than one value in such a method you may get inconsistent values for them when another thread modifies the data between the accesses. I agree with rubberman, the storeUser method should be synchronized on the target data store object.

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 
Means unless we are updating or modifying something there is no need to make such methods synchronous?


As long as you are only using local, and not static or global variables in your method, you should be fine. As we have stated however, the storeUser() method should either be synchronous, or a lock applied to the data store. If the storeUser() method does a lot and being synchronous could introduce unnecessary latencies, then use a lock only for access to the data store.

rubberman
Posting Virtuoso
1,565 posts since Mar 2010
Reputation Points: 277
Solved Threads: 179
 

Thanks a lot for the replies, :)
cleared my doubt

warlord902
Junior Poster
120 posts since Dec 2010
Reputation Points: 19
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: