File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Safe Code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Safe Code" Watch "Thread Safe Code" New topic

Thread Safe Code

Kousik Majumder
Ranch Hand

Joined: Sep 30, 2007
Posts: 237

Is the class Thread Safe?
If not how can I make that one Thread Safe?

Thanks in Advance,
Gaurav Bhatia
Ranch Hand

Joined: Jan 01, 2007
Posts: 49
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.

You can also make doThings as a static synchronized method.

Hope this clarifies.

~Gaurav<br />SCJP5
I agree. Here's the link:
subject: Thread Safe Code
Similar Threads
It's not a secret anymore!