Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why you should never use synchronized on Optional java object

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 ???

like image 713
Mohammed Housseyn Taleb Avatar asked Jul 10 '19 11:07

Mohammed Housseyn Taleb


People also ask

Why optional should not be used for fields?

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.

Why is null better than optional?

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.

Should you use optional in Java?

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.

Should Optional be used as a parameter?

Java static code analysis: "Optional" should not be used for parameters.


1 Answers

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.

like image 175
Michael Avatar answered Oct 22 '22 18:10

Michael