This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Safe Code

 
Kousik Majumder
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Is the class Thread Safe?
If not how can I make that one Thread Safe?
 
Gaurav Bhatia
Ranch Hand
Posts: 49
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The class is NOT thread safe.

Reason : If two instances of the same class are created, it will create two different threads. Now, if both threads are calling this method doThings() which is synchronized, they are getting lock on their respective object and not on the "Class object".
And a static variable is being shared between both the instances.
To make this thread safe, a lock on the .Class instance should be acquired because only one .class instance exists.

Or
You can also make doThings as a static synchronized method.

Hope this clarifies.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Similar Threads