• 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
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Thread Safe Code

 
Ranch Hand
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



Is the class Thread Safe?
If not how can I make that one Thread Safe?
 
Ranch Hand
Posts: 49
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic