File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes thread safety ? 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 » Java » Threads and Synchronization
Bookmark "thread safety ?" Watch "thread safety ?" New topic

thread safety ?

Edward Chen
Ranch Hand

Joined: Dec 23, 2003
Posts: 798

In the coding below, is it thread safety ? My answer is yes. because the method is synchronized and the variable is private so that no other way to change X value.

What do you think ?

Henry Wong

Joined: Sep 28, 2004
Posts: 20538

What about two different threads call the doit() methods of two different Test objects at the same time?


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Alex Hurtt
Ranch Hand

Joined: Oct 26, 2010
Posts: 98
It is NOT thread safe. You are synchronizing an instance method that modifies a static variable. Each instance of the class Test has its own lock ensuring that no 2 threads will access the doit() method on the same single instance of Test simultaneously. But nothing stops somebody from constructing multiple instances of Test and starting all of them up. In this case they will all be accessing the same x because it is static and you are not synchronizing on the Test class lock. You are synchronizing on an instances lock when you synchronize an instance method.
Suhrid Karthik
Ranch Hand

Joined: Aug 31, 2008
Posts: 58

Perhaps think about what you can change in your code to synchronize on the class lock instead of the instance lock.
Lester Burnham

Joined: Oct 14, 2008
Posts: 1337
Not a direct response, but be sure to read
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46437
Too difficult a question for beginners. Moving thread.
I agree. Here's the link:
subject: thread safety ?
jQuery in Action, 3rd edition