?
Solved

What is thread safe class??

Posted on 2004-11-30
24
Medium Priority
?
390 Views
Last Modified: 2008-02-01
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
0
Comment
Question by:sudhakar_koundinya
  • 8
  • 8
  • 4
  • +3
24 Comments
 
LVL 3

Assisted Solution

by:udo_borkowski
udo_borkowski earned 100 total points
ID: 12704386
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
 
LVL 13

Assisted Solution

by:petmagdy
petmagdy earned 300 total points
ID: 12704409
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
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 12704432
petmagdy,

Can u explain ur approach using sme example

Regards
Sudhakar
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 12704441
udo_borkowski,

I tried to explain the same as mentioned in article. But he was not conveinced
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 300 total points
ID: 12704445
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
 
LVL 13

Assisted Solution

by:petmagdy
petmagdy earned 300 total points
ID: 12704460
simple example this is a Thread safe class:

public class Safe
{
 //no member fields

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

}
0
 
LVL 8

Accepted Solution

by:
rk_radhakrishna earned 100 total points
ID: 12704481
I hope this example may helps you,
http://www.mindprod.com/jgloss/threadsafe.html
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 300 total points
ID: 12704522
>>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
 
LVL 13

Assisted Solution

by:petmagdy
petmagdy earned 300 total points
ID: 12704527
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 12704531
>>in the real world are usually ones that have been *made* thread safe

Or, let's say "are of often ones ..."
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12704534
>>in the real world are usually ones that have been *made* thread safe

Or, let's say "are often ones ..."
0
 
LVL 13

Expert Comment

by:petmagdy
ID: 12704547
yes CEHJ I was talking about classes safe by nature without need to synchronized and offcourse classes use synchronized to become Thread safe
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 12704569
0
 
LVL 21

Assisted Solution

by:MogalManic
MogalManic earned 200 total points
ID: 12704602
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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12704631
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 12704643
>>soo just as a summary thread safe classes are 2 types

No - there's no need to make a distinction between types
0
 
LVL 21

Assisted Solution

by:MogalManic
MogalManic earned 200 total points
ID: 12704689
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
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 300 total points
ID: 12704715
>>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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12704765
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 12704823
>>relaxe CEHJ

What makes you think i'm not relaxed? ;-)
0
 
LVL 13

Expert Comment

by:petmagdy
ID: 12704862
because u told me before u don't sleep, thats why I thought u need relaxation ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12704878
8-)
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 12704881
>>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
 
LVL 13

Expert Comment

by:petmagdy
ID: 12709237
thanks sudhaker, tell me if u need my resume ;-)
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month14 days, 4 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question