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.

Recommended Answers

All 5 Replies

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.

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?

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.

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.