This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes  Thread safe class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark " Thread safe class" Watch " Thread safe class" New topic
Author

Thread safe class

Saral Saxena
Ranch Hand

Joined: Apr 22, 2011
Posts: 202

Hi Folks,
I was going through the concept of thready safety...please explain the concept of Thread safe class..with the help of a small detailed example ..if possible..!! Does it mean the class which is synchronized completely and that would not cause a deadlock situation in nearby future..!!
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3573
    
  14

A class is thread-safe if its contracts still hold when you perform operations on the class by different threads at the same time. This means thread safety is for a large part determined by what's in the contracts of the class and its methods; therefore there are no easy rules to guarantee safety.

If a get() method promises in its contract to return the value last passed during the invocation of some set() method, then you need to take extra steps to ensure thread-safety. In the end, you just need to think about it logically, and you need to determine all the points where things can go wrong. In general, methods that only get data have to be synchronized in some way if the data they retrieve can change during their execution. Methods that change data should always be synchronized. There's more to it though.

The easiest way to make a class thread safe is to make it immutable. If data can't change, then all threads will always see the same data.

Note that making a class thread-safe is only rarely desirable. Only classes that *know* they are going to be used by multiple threads should be thread-safe. Other classes should make no promises. The reason for this is that thread-safety usually comes with a performance penalty.
 
wood burning stoves
 
subject: Thread safe class
 
Similar Threads
Thread Safe
thread safe classes...
true or false......implicit obj's threadsafe?
question about action class
Is Struts Action class Thread Safe?