aspose file tools*
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
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "thread safety ?" Watch "thread safety ?" New topic
Author

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
author
Sheriff

Joined: Sep 28, 2004
Posts: 19004
    
  40

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

Henry


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
Rancher

Joined: Oct 14, 2008
Posts: 1337
Not a direct response, but be sure to read http://faq.javaranch.com/java/ExtendingThreadVsImplementingRunnable
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39887
    
  28
Too difficult a question for beginners. Moving thread.
 
Consider Paul's rocket mass heater.
 
subject: thread safety ?