Ernest Friedman-Hill wrote:
Originally posted by Saurabh Agrawal:
Can anyone tell me what is the meaning of thread safe precisely ??
Imagine a Person object, with many member variables; among these are three variables that represent the street, city, and postal code where they live.
You are writing a function which prints mailing address labels.
Now, imagine that one person is moving to another city, which requires changing those three variables in one Person objects. Let's say that person has just filled in a form on the Web which lets him change his address. The Web application has to set those three variables, one after another. The first one it sets is the new street address. The city and postal code are next.
Now imagine, that just at the instant that the street address is changed, your function (running in another thread) starts to print an address label for that person. The address label includes the person's name, their new street adress, but their old city and postal code. Any mail with that label on it will never be delivered correctly!
The problem is that the address-setting operation is not thread-safe. During the short time that the Web application is changing those three fields, the Person object is in an invalid state. If another thread looks at that Person's address variables during that time, it will get incorrect information.
To make this operation thread safe, you must write the methods in such a way that the address-setting process cannot be interrupted by any other thread; while the three variables are being set, no other thread can read any of them. This can be accomplished in Java using synchronized methods.
This is a far better explanation for a beginner....and explains concisely. Loved the explanation! Thanks!