Is it safe to use Thread
's methods like setName
/ getName
and some others from different threads? API does not say anything, but judging by the source code
private char name[];
public final void setName(String name) {
checkAccess();
this.name = name.toCharArray();
}
public final String getName() {
return String.valueOf(name);
}
it seems that it may cause memory consistency errors.
A method will be thread safe if it uses the synchronized keyword in its declaration.
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
A POJO can't be thread safe. A POJO is just data, and thread safety is not a property of data alone: Thread safety is a property of the methods that access the data.
Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.
Thread.getName()
is a property than can be queried by anyone at any time. For example, a monitor utility constantly queries names of all threads. So the method has to be thread safe, otherwise, there's no clear protocol about who can safely access it and when.
Though it's always been puzzling why Thread
uses a char[]
to save its name, you are raising a more important question, getName()
is obviously not correctly synchronized. If one thread does setName("abcd")
, another thread may observe getName()->"ab\0\0"
.
I'll post the question to concurrency-interest list. see http://cs.oswego.edu/pipermail/concurrency-interest/2013-March/010935.html
"API does not say anything"
If an API does not say anything, than you never can asume that a method /class is thread safe.
As you can see from the source code, the acess to name
is not mutual exclusive.
But for me it seems, that name
has either the old value or the new one, nothing in between, so it looks safe for must uses of get/setName().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With