What is thread safe class??

Hello All,

I attended an interview one hr back. And one of the question asked by interviewer is what is thred safe class. The answer what I gave is not conveinced the interviewer and also the answer what I getfrom  him  also is not right to me as per my perceptions.

I have tried to conveince him using synchronizations concepts. But he has not accepted my explanation

So plz let me know what you think abt the thread safe class??

Thanks
Sudhakar chavali
LVL 14
sudhakar_koundinyaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

udo_borkowskiCommented:
A nice explaination is given here: http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-threadsafe.html 
(notice this article contains 3 pages)


0
petmagdyCommented:
thread safe class is a class dosn't need thread acccess managment, in other word this is a class that have no state to be access managed in MultiThread enviroment, in other words stateless class is Thread Safe :-)

could u please forward my Resume to this oppurtunity it seems i am a good candidate :-P
0
sudhakar_koundinyaAuthor Commented:
petmagdy,

Can u explain ur approach using sme example

Regards
Sudhakar
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

sudhakar_koundinyaAuthor Commented:
udo_borkowski,

I tried to explain the same as mentioned in article. But he was not conveinced
0
CEHJCommented:
A thread safe class in my mind is one whose internal state cannot be left inconsistent through concurrent access. That consistency problem should probably be extended to encompass the point of view of a client of that class too
0
petmagdyCommented:
simple example this is a Thread safe class:

public class Safe
{
 //no member fields

 public static void foo()
 {
   //bla bla
 }

}
0
rk_radhakrishnaCommented:
I hope this example may helps you,
http://www.mindprod.com/jgloss/threadsafe.html
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CEHJCommented:
>>thread safe class is a class dosn't need thread acccess managment

That's much the same as what i've said, but your emphasis is somewhat misleading. In your definition, this could imply that a class with deliberate synchronization code to render it thread safe is by definition *not* thread safe ;-) Thread safe classes in the real world are usually ones that have been *made* thread safe through synchronization, not usually ones that didn't need synchronization in the first place.

0
petmagdyCommented:
another Thread Safe Class is Immutable classes like this:

public class Cordinate
{
 int x;
 int y;
 
 public Cordinate()
 {
   // initialize x,y
 }

 Cordinate(int x, int y)
 {
  // initialize x,y
  }

  //create getter methods for x,y and no setters

  public Cordinate moveToNewCordinate(int deltaX, int deltaY)
  {
             return new Cordinate(x+deltaX, y+deltaY);
  }
}
0
CEHJCommented:
>>in the real world are usually ones that have been *made* thread safe

Or, let's say "are of often ones ..."
0
CEHJCommented:
>>in the real world are usually ones that have been *made* thread safe

Or, let's say "are often ones ..."
0
petmagdyCommented:
yes CEHJ I was talking about classes safe by nature without need to synchronized and offcourse classes use synchronized to become Thread safe
0
sudhakar_koundinyaAuthor Commented:
0
MogalManicCommented:
The simplest way to create a thread safe class is to NOT use any class level variables (i.e. a class with just methods only).  This is not a hard and fast rule, you can create final variables.  Final variables are OK because you must initialize them at class construction time.  This way there is no way that their state can change from call to call.

If you absolutly MUST have non-final class variables, then you must syncronize those methods that will change and/or modify those variables.  Keeping in mind, that if other classes obtain a reference to your state variables, they are storing a snapshot of your classes state.  For example this would NOT be a thread safe class:

public foo
{
    private String name;
   
    public syncronized setName(String name)
    {
        this.name=name
    }

   public String getName()
   {
      return name;
   }
}

This is NOT thread safe because it is exposing the variable name through the getName() method.  One thread could call setName("A") and then call getName() and NOT get "A" back.  This is because another thread can call setName() right after the first thread call setName().  There is no guarantee on what the name will be at any given point in time.

This is an example of a thread safe class:

public SystemCache
{
   private Map cache=new HashMap();

   public Object syncronized find(String key)
   {
        Object found=cache.get(key);
        if (found==null) {
            found = TransactionLayer.get(key);
            cache.put(key, found);
         }
         return found;
   }
}

This is thread safe because it does not its method returns the same object regardless of the state of the cache.  It does not expose the implementation (the HashMap) so the user of the class need not know that the items are cached at all.
 
0
petmagdyCommented:
soo just as a summary thread safe classes are 2 types, the first type is classes thread safe by nature like (Statless or no member variables, Immutable) and second type those who have member variables and hence need Syncronization managment
0
CEHJCommented:
>>soo just as a summary thread safe classes are 2 types

No - there's no need to make a distinction between types
0
MogalManicCommented:
Just because the methods are syncronized does not make it thread safe (see my example above).  If you need to store state information in a class, you need to then look on how that class is used and make sure that the users cannot query your class and then make assumtions on its state.  
0
CEHJCommented:
>>Just because the methods are syncronized does not make it thread safe

Indeed not. To summarize my earlier answer:

A thread safe class is one whose internal state cannot be left inconsistent through concurrent access
0
petmagdyCommented:
relaxe CEHJ,
classification of thread safe classes or no classification who cares!
 i am just trying to earn the open oppurtunity to myself ;-)
have a nice day all
cheers!

0
CEHJCommented:
>>relaxe CEHJ

What makes you think i'm not relaxed? ;-)
0
petmagdyCommented:
because u told me before u don't sleep, thats why I thought u need relaxation ;-)
0
CEHJCommented:
8-)
0
sudhakar_koundinyaAuthor Commented:
>>could u please forward my Resume to this oppurtunity it seems i am a good candidate :-P

I included some extra points for you because of ur sense of humour. I saw some other comments from other thread aslo. I like your sense of humour ;-)
0
petmagdyCommented:
thanks sudhaker, tell me if u need my resume ;-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.