aspose file tools
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 Groovy Fundamentals video training course this week in the Groovy forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark " Thread safe class" Watch " Thread safe class" New topic

Thread safe class

Saral Saxena
Ranch Hand

Joined: Apr 22, 2011
Posts: 203

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

Joined: Sep 20, 2010
Posts: 3791

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