I m learning about java optional wrapper, to do so I m reading the following tutorial
however I have a simple question that is not answered in the article: in item 25: Avoid Using Identity-Sensitive Operations on Optionals they are mentioning to NEVER use an optional object in a synchronized way like this:
Optional<Product> product = Optional.of(new Product());
synchronized(product) {
...
}
but there is no explanation why, so please would any one here explain to me why this is a bad practice ???
You should almost never use it as a field of something or a method parameter. So the answer is specific to Optional: it isn't "a general purpose Maybe type"; as such, it is limited, and it may be limited in ways that limit its usefulness as a field type or a parameter type.
In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.
Why Do Developers Need Optional in Java? Optional is generally used as a return type for methods that might not always have a result to return. For example, a method that looks up a user by ID might not find a match, in which case it would return an empty Optional.
Java static code analysis: "Optional" should not be used for parameters.
Because
[value-based classes] are freely substitutable when equal, meaning that interchanging any two instances x and y that are equal according to
equals()
in any computation or method invocation should produce no visible change in behavior"
Source (Oracle)
You can not freely substitute X and Y if there is an intrinsic lock on one of them, since doing so may produce a change in behaviour.
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