Vassili ...
SCJP 5.0, SCWCD 1.4, SCJA 1.0
cmbhatt
But my question was "How come method toString() thread safe?"
cmbhatt
Originally posted by Chandra Bhatt:
The source says, the method toString() is thread safe and StringBuffer can
be replaced with StringBuilder to increase the performance.
I don't understand this. Please help.
cmbhatt
Originally posted by John Stone:
firstName and lastName are shared, but since they are both immutable, and assignment of reference is most likely an atomic operation,
toString can be considered as thread-safe, because there is no way to get into inconsistent state
cmbhatt
Originally posted by John Stone:
firstName and lastName are shared, but since they are both immutable, and assignment of reference is most likely an atomic operation,
toString can be considered as thread-safe, because there is no way to get into inconsistent state
Originally posted by Chandra Bhatt:
Hi John,
I find point in what you said. "Atomic operation" I simply like this.
But I couldn't get you exactly regarding the immutability issue.
If one thread modifies the firstname and last name outside the method toString(), why wont it affect the meaning of toString() method.
Anyhow, all the threads will be sharing the same member variables.
Please clarify what you said.
cmbhatt
firstName and lastName are not declared as volatile, so the toString() method may get an older version of the object. There is also a race condition, in that one name may be changed, but not the other, giving you a weird name combination.
cmbhatt
Originally posted by Henry Wong:
firstName and lastName are not declared as volatile, so the toString() method may get an older version of the object. There is also a race condition, in that one name may be changed, but not the other, giving you a weird name combination.
However, you are right, in that reference assignments *are* atomic. Either it will get the old value or the new value, it will not get a reference value that is a combination of the two possible references.
Regardless, this problem exist whether you are using StringBuffer or StringBuilder.
Henry
[ May 05, 2007: Message edited by: Henry Wong ]
I guess everyone has an angle. Fine, what do you want? Just know that you cannot have this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
|