Kasun
Kasun

Reputation: 561

How Method passing parameters behave in multi-threaded enviornment

By definition Local variables are the variables declared within a method. Multiple threads maintain them in their own stacks. I need to understand how this works with passing Method parameters in multi-threaded environment. ?

For example - assume User is a instance variable and pass to its local synchronized methods.

public static synchronized registerUser(User user,int count){}

public synchronized registerUser(User user,int count){}

In the above example , I am passing a Object and primitive.

  1. How the passing parameters manage in static methods with multiple threads? (Objects,primitives)

  2. How the passing parameters manage in non-static methods with multiple threads? (Objects,primitives) ?

3.Active thread always acquire the method lock that it executes. As User object reference is working under synchronized context will that reference available for other threads to use in unlock methods?

Upvotes: 0

Views: 241

Answers (1)

Nick Holt
Nick Holt

Reputation: 34311

The static method locks on the class, while the member method locks on the object.

Java uses a pass-by-value, which in the case of a primitive is the value and in the case of an object is the reference to the object.

In your methods:

  • there is no lock on the user, which could be modified by another thread via a different reference to it while the synchronized method being invoked.
  • the value of the primitive count cannot be modified such that the method would see the modification after any method is invoked.

Upvotes: 0

Related Questions