Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all Thread methods (like getName/setName) thread-safe?

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.

like image 531
Evgeniy Dorofeev Avatar asked Mar 14 '13 20:03

Evgeniy Dorofeev


People also ask

How do I know if a method is thread-safe?

A method will be thread safe if it uses the synchronized keyword in its declaration.

Which of the following are thread-safe?

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.

Is POJO thread-safe?

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.

What is meant by thread-safe?

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.


2 Answers

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

like image 79
ZhongYu Avatar answered Sep 27 '22 23:09

ZhongYu


"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().

like image 29
AlexWien Avatar answered Sep 28 '22 00:09

AlexWien