Reputation: 31
I am accessing a private String field from multiple threads which run a nested class.
I am aware that String objects are immutable, so passing a String as an argument should always be safe. But how about accessing the exact same field? I assume it is not thread safe?
Upvotes: 0
Views: 1291
Reputation: 85779
It is still thread safe because you're only accessing to the field. The problem will be if some thread will try to modify the field (its state or change the whole object reference) while other threads are getting the value of this variable at the same time.
Usually, you create a class that implements Runnable
and pass the necessary arguments:
class MyTask implements Runnable {
private final String needThis;
public MyTask(String needThis) {
this.needThis = needThis;
}
@Override
public void run() {
//do your task using needThis variable here...
}
}
This can be applied for other kind of arguments as well. Also, it is better to send object references of immutable classes (like String
) as data for your threads.
Upvotes: 1
Reputation: 120
If you are just reading the field it's always thread safe. Make field final so that compiler checks if you are changing value?
private final String theField = "TheValue"
Upvotes: 2