I'd like to understand why Java 8 Optionals were designed to be immutable. Is it just for thread-safety?
Optional is considered mutable #57.
Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.
Immutable objects are thread-safe so you will not have any synchronization issues. Immutable objects are good Map keys and Set elements, since these typically do not change once created. Immutability makes it easier to parallelize your program as there are no conflicts among objects.
There are a number of advantages to using immutable data. It's inherently thread safe, because since no code can alter its content, it's guaranteed to be the same no matter what code is accessing it.
Optionals are for passing things around. If you give something to someone and then change its contents, they will be very surprised, and not in a good way.
Optional is considered a value object, and should be immutable to help reduce their ability to make you pull your hair out tracking down a bug at 3am. You can read here for a bit more on the topic:
http://martinfowler.com/bliki/ValueObject.html
http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
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