Link to home
Start Free TrialLog in
Avatar of vi_sharma
vi_sharma

asked on

Should calls to new() be protected by synchronized block?

As we know, each thread is awarded a Java stack, which contains data no other thread can access, including the local variables, parameters, and return values of each method the thread has invoked. What about the object references?

Consider  the following method:

Myclass1 func(Myclass2 obj2)
{
 Myclass1 obj1 = new Myclass1(obj2);
 return obj1;
}

Assume that this method is being called by many threads simultaneously, each passing its own value for obj2, should I protect th execution of line Myclass1 obj1 = new Myclass1(obj2) through a synchronized block?
SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of vi_sharma
vi_sharma

ASKER

True, obj1 will be local variable for each thread, but the object it refers to,  which is created using new MyClass(obj2) won't be. Each thread may pass a different value for obj2, so I am wondering if it will lead to some inconsistencies?
See any book on Principles of Programming languages to know how a new activation record is created for each function call having its own copy of local variables, etc
Mayank, this is little more for me to grasp. Could you please give a dumbed-down explanation of how a new activation record relates to my query on objects on heap being shared by threads?

Thanks.
Whenever a function/ method is called, a new record for it is created on the stack. This is the activation record of the function that stores its state - in terms of parameter-values, values of local variables, return-address, etc. It is separate for each function 'call', so even if the same function is called 3 times from 3 different places, they will have 3 separate records. The references could refer to same objects, though, in the heap, if they are assigned that way to a shared object.
In your case, since obj2 is referring to a different object in every 'call', it is fine.
Mayank, thanks. But I still didn't get this - would a new MyClass() executed by thread 1 would result in return reference value to be falsely used by thread 2? If so,  I need to use synchronized block to prevent that.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks! clear now.
Glad to help - you should've split because objects' comment was also correct. I'll ask Venabili (our Page Editor).
Cool. That's fine - you can ask her(him?). I would prefer 30-20 split (30 for you as you spent more time on this with me :-))
Done - asked her.