Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is String get/set threadsafe?

Let's say I have the following,

public class Foo{
    private String bar;

    public String getBar(){
        return bar;
    }

    public void setBar(String bar){
        this.bar = bar;
    }
}

Are these methods automatically threadsafe due to the immutable nature of the String class, or is some locking mechanism required?

like image 460
mre Avatar asked Feb 25 '13 17:02

mre


People also ask

What is thread-safety in Java?

When a thread is already working on an object and preventing another thread on working on the same object, this process is called Thread-Safety. There are four ways to achieve Thread Safety in Java. These are: Using Synchronization.

Are Java strings thread safe?

With this program you can see that String is immutable so original String won't be changed but String reference can still be changed with multiple threads. So Java Strings are thread safe here means when the shared String is changed it creates a new copy for another thread that way original String remains unchanged.

How to create thread-safe collections in Java?

You already know that, the Java Collections Framework provides factory methods for creating thread-safe collections. These methods are in the following form: These factory methods wrap the specified collection and return a thread-safe implementation. Here, XXX can be Collection, List, Map, Set, SortedMap and SortedSet implementations.

How thread-safe is a method with a specific input?

Given a specific input, it always produces the same output. The method neither relies on external state nor maintains state at all. Hence, it's considered to be thread-safe and can be safely called by multiple threads at the same time.


2 Answers

No, this is not threadsafe. Foo is mutable, so if you want to ensure that different threads see the same value of bar – that is, consistency – either:

  • Make bar volatile, or
  • Make the methods synchronized, or
  • Use an AtomicReference<String>.

The reads and writes of bar are themselves atomic, but atomicity is not thread safety.

http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html


For in-depth coverage of Java concurrency, grab a copy of Java Concurrency in Practice (aka JCIP).

like image 185
Matt Ball Avatar answered Oct 04 '22 05:10

Matt Ball


You're setting references, and as such String's immutability doesn't come into play. You're not affecting the contents of String.

like image 21
Brian Agnew Avatar answered Oct 04 '22 07:10

Brian Agnew