0

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?

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Another good way, but in my case the String is set dynamically so I'll go with the other way.
1

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.

3 Comments

Okay, yes of course. But I would like to code it in a way that possible future adjustments do not break my code :). So passing the String to the constructor (of the Runnable) is probably the nicer way?!
@ManishMudgal I think you haven't understood the problem.
This solution is the one you should go with, because it does not have shared state. This is usually a good thing unless you really, really need to (and you usually don't).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.