Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is this thread safe?

 
Kerry Wilson
Ranch Hand
Posts: 254
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is TestThread number thread safe in following example?



I am thinking it is, but, just to be safe....
 
Yuan Ye
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Each thread will have its own copy of number. it is thread safe.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As TestThread is used in this example program, there will be no race conditions. But as a generally Thread-safe class, I'd actually say TestThread fails because its member variable "number" is not private. Multiple threads could access that member in an unsynchronized way.

You might call this a small detail, but in a real program, this is where threading problems come from.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This isn't strictly necessary once you made number private, but I'd also remove the initialization to "-1" and declare it as final. It not better communicates intend, but also decreases of likeliness of bug injection due to later modification of the code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic