• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread safe class

 
Ranch Hand
Posts: 203
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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..!!
 
Saloon Keeper
Posts: 15524
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
reply
    Bookmark Topic Watch Topic
  • New Topic