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?
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.
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.
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.
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.
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:
bar
volatile
, orsynchronized
, orAtomicReference<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).
You're setting references, and as such String
's immutability doesn't come into play. You're not affecting the contents of String
.
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