Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Java Optionals immutable?

Tags:

java

optional

I'd like to understand why Java 8 Optionals were designed to be immutable. Is it just for thread-safety?

like image 502
Julian A. Avatar asked Jan 01 '16 02:01

Julian A.


People also ask

Are optionals mutable?

Optional is considered mutable #57.

Why are the objects immutable in Java?

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.

Why would one want to make fields immutable?

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.

What is the advantage to immutable data wrappers?

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.


2 Answers

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.

like image 165
Svante Avatar answered Oct 21 '22 07:10

Svante


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

like image 24
michael salmon Avatar answered Oct 21 '22 07:10

michael salmon