File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Is this thread safe? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Is this thread safe?" Watch "Is this thread safe?" New topic
Author

Is this thread safe?

Kerry Wilson
Ranch Hand

Joined: Oct 29, 2003
Posts: 254
Is TestThread number thread safe in following example?



I am thinking it is, but, just to be safe....


http://www.goodercode.com
SCJP 1.4
Yuan Ye
Ranch Hand

Joined: Mar 05, 2003
Posts: 172
Each thread will have its own copy of number. it is thread safe.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is this thread safe?
 
Similar Threads
a.run() and a.start()
Doubt on Thread state
Thread
again Thread
Whizlab question