Why immutable objects are thread safe in java




















Some languages e. C let us represent arrays using just a pointer to their start address, others also store their length. Let's do the latter, in pseudocode:. Now a2 is the array [d, e]. Crucially, both a1 and a2 are using the same part of memory: the elements d and e aren't copied. This has a few consequences:. If we make our arrays mutable then we have to be very careful about point 4 : values in one part of the program might be affected by other parts of the program which seem unrelated, if they happen to be sharing the same pieces of memory.

Note that this isn't just an issue for concurrent applications; such "aliasing" can undermine a lot of assumptions made by our algorithms, causing them to misbehave. The possibility of aliasing also prevents some optimisations being performed by the compiler. We can avoid this problem, and problem 3 , by having some of our functions make copies of the memory contents, and return pointers to those copies.

This is slow and memory-intensive compared to slicing. Many libraries will copy "defensively", i. If we make our arrays immutable then point 4 doesn't matter. Point 3 is still a problem, which can also be solved by copying, but in practice this is much less of a concern: having lots of large arrays sharing the same memory is an advantage ; the problem is when we're finished using a large array, but we still need a small slice of it.

In this case we must copy that slice in order to free up the large array; however, that only requires copying a small amount of data by definition , so the cost is usually small. Immutable data can hence make it easy to write fast, safe, low-memory programs.

On the other hand, with mutable data we may be forced to sacrifice one of these e. Of course, constructing and garbage-collecting lots of tiny immutable values can also slow things down, so there's a balance to be struck. Also note that this isn't limited to arrays; there's a whole family of "functional datastructures" which are designed so that common operations can share large parts of the memory without defensive copying; the most common is a singly-linked list, where prepending an element can share the entire "tail".

Take any immutable concept even as simple pi. Threads can share the definition of pi now and read it knowing its value will not change, that data races are not possible. I don't know why there is a mental block here when we introduce aggregates like whole structs or objects or arrays. The same concept applies. If it don't change, it's safe to read in parallel with the assumption that it won't change.

Immutables are safe for concurrent read access because simultaneous write access is not possible. That's really all there is to it. You are safe to read it in parallel without the assumption that it could change at any time.

As for atomic reference counters that are shared, if you can get away from any sort of shared data between threads, I would always err on that side when possible. If you can't get away from it, it's worth noting that simply ensuring that increments and decrements to your reference counter are atomic may not be atomic enough. You might need a broader operation to complete or fail completely in an atomic way than just incrementing or decrementing the counter. Sign up to join this community.

The best answers are voted up and rise to the top. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Learn more. Are immutable objects important only in multi-threaded applications and if so, how are shared immutable objects useful? Ask Question. Asked 1 year, 1 month ago. Active 1 year, 1 month ago. Viewed 5k times. Improve this question. You might also be interested in how immutable structures work.

For example, you should be able to find a lot on how they work in Clojure. Are you aware that Java's String class is an immutable class? Do you really think it was only made immutable because of multithreading in mind? Do you think the String class is useful despite the fact String objects cannot be changed?

A great thing about immutable objects is that you don't need to make a defensive copy every time you want to return a value to a caller.

With mutable objects, making defensive copies is widely done. With immutable objects, you don't have to make defensive copies all the time. Defensive copying is exhausting ThomasWeller: see softwareengineering. C has no String class, of course, but the equivalent are arrays of characters, and before C89, there was no way to declare such an array as "immutable". Java and C have no notion of "const" parameters, in those languages it is common to use immutable classes instead.

Show 5 more comments. Active Oldest Votes. No, immutable objects are quite useful in general. Improve this answer. Telastyn Telastyn k 29 29 gold badges silver badges bronze badges. See e. Is it actually a good idea to do this with counter?

Because if two threads grab an old state, increment it, and write references one after another, you'll end up with counter incremented once and not twice. Telastyn "creating an object and assigning it to a variable are not independent reorderable operations". That's only true for final fields. Non-final fields can be written to after the half-created object has already been published. But yes as long as you make all fields final a reasonable assumption it'll work.

I don't consider incrementing a counter thread-safe. It's actually very tricky to define it. I would say that thread safe code has an expected behavior in multi-thread environment. I'll let you define "expected behavior" String is considered immutable. Looking at its implementation, we can deduce one thing: an immutable string can change its internal state in this case, the hashcode which is lazy loaded as long as it is not externally visible.

Now I am going to rewrite the hashcode method in a non-thread safe way:. As you can see, I have removed the local variable h and I have instead affected the variable hash directly.

This implementation is NOT thread safe! If several threads call hashcode at the same time, the returned value could be different for each thread. The question is, 'is this class immutable? We can so conclude that String is immutable because it is thread safe and not the opposite. What's the point of saying "Use an immutable object, it is thread-safe!

But take care, you have to make your immutable object thread-safe! This code is not thread safe because SimpleDateFormat. Is this object immutable? Good question! We have done our best to make all fields not modifiable, we don't use any setter or any methods that let us suggest that the state of the object will change. Actually, internally SimpleDateFormat changes its state, and that's what makes it non-thread safe.

Now String is an immutable class, whenever a thread tries to change it, it simply end up creating a new object. Now since there is no synchronize, volatile or final keywords to tell compiler to skip using its intelligence for optimization any reordering or caching things , this code can be run in following manner.

So, Immutable objects are always thread-safe, but their references may not be. In addition to other answers posted already, immutable objects once created, they cannot be modified further. Hence they are essentially read-only.

And as we all know, read-only things are always thread-safe. Even in databases, multiple queries can read same rows simultaneously, but if you want to modify something, you need exclusive lock for that. An immutable object is an object that is no longer modified once it has been constructed. If in addition, the immutable object is only made accessible to other thread after it has been constructed, and this is done using proper synchronization, all threads will see the same valid state of the object.

If one thread is creating populating the reference variable of the immutable class by creating its object and at the second time the other thread kicks in before the first thread completes and creates another object of the immutable class, won't the immutable class usage be thread unsafe? What makes you think so? An object's thread safety is completely unaffected by what you do to other objects of the same class. They are trying to say that whenever you pass something from one thread to another, even if it is just a reference to an immutable object, you need to synchronize the threads.

For instance, if you pass the reference from one thread to another by storing it in an object or a static field, that object or field is accessed by several threads, and must be thread-safe. Thread safety is data sharing safety, And because in your code you make decisions based on the data your objects hold, the integrity and deterministic behaviour of it is vital.

Imagine we have a shared boolean instance variable across two threads that are about to execute a method with the following logic. If you run continuously in a single thread loop, you will have a deterministic output which will look like:. But, if you ran the same code with two threads, then, the output of your output is not deterministic anymore, the reason is that the thread A can wake up, read the flag, see that is false, but before it can do anything, thread B wakes up and reads the flag, which is also false!!

So both will print false And this is only one problematic scenario I can think of As you can see, this is bad. If you take out the updates of the equation the problem is gone, just because you are eliminating all the risks associated with data sync.

It is important to note though, that immutable objects are not always the solution, you may have a case of data that you need to share among different threads, in this cases there are many techniques that go beyond the plain synchronization and that can make a whole lot of difference in the performance of your application, but this is a complete different subject.

Immutable objects are important to guarantee that the areas of the application that we are sure that don't need to be updated, are not updated, so we know for sure that we are not going to have multithreading issues.

Immutability doesn't imply thread safety. In the sense, the reference to an immutable object can be altered, even after it is created. With regards to 'it may be necessary to ensure Stack Overflow for Teams — Collaborate and share knowledge with a private group.



0コメント

  • 1000 / 1000