File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread safety ?

 
Edward Chen
Ranch Hand
Posts: 798
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Marshal
Pie
Posts: 20831
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What about two different threads call the doit() methods of two different Test objects at the same time?

Henry
 
Alex Hurtt
Ranch Hand
Posts: 98
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 58
Eclipse IDE Java Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps think about what you can change in your code to synchronize on the class lock instead of the instance lock.
 
Lester Burnham
Rancher
Posts: 1337
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not a direct response, but be sure to read http://faq.javaranch.com/java/ExtendingThreadVsImplementingRunnable
 
Campbell Ritchie
Sheriff
Pie
Posts: 47231
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Too difficult a question for beginners. Moving thread.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic