• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

thread safety ?

 
Ranch Hand
Posts: 798
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?

 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What about two different threads call the doit() methods of two different Test objects at the same time?

Henry
 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 58
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Rancher
Posts: 1337
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not a direct response, but be sure to read http://faq.javaranch.com/java/ExtendingThreadVsImplementingRunnable
 
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Too difficult a question for beginners. Moving thread.
 
reply
    Bookmark Topic Watch Topic
  • New Topic